Answer the question
In order to leave comments, you need to log in
Why does an array with a limited number of values take more than it should?
I am quite new to java, and as befits all beginners, I decided to write a calculator, but limited in characters. So I have an array in which there are only 3 cells, but for some reason when I add the 4th value to it, it does not give me an error, but simply adds all 4 values to the list, why?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers to be counted:");
String calc = scanner.nextLine();
try {
String[] subCalc = new String[3];
subCalc = calc.split(" ");
for (int i = 0; i < subCalc.length; i++) {
System.out.println(subCalc[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Only 3 characters are allowed!");
System.out.println("2 + 2 | Yes");
System.out.println("2 + 2 + 2 | No");
}
}
}
Answer the question
In order to leave comments, you need to log in
calc.split(" ")
returns a new array of a different size and overwrites the previous one in the subCalc variable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question