Ok so I'm working on my accounting application and heres what i got so far:
public class Accounting {
public static void main(String[] args) {
while(true){
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
String[] parts = userinput.split(" ");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
int a = Integer.parseInt(part1);
float r = Float.parseFloat(part2);
int t = Integer.parseInt(part3);
double Total = a*Math.pow(1.0+(r/100.0), t);
String[] result = userinput.split(" ");
if (result.length == 3) {
System.out.println(Total);
} else {
System.out.println("Usage: a r t (a is the amount, r is the rate, and t is the time)");
}
}
}
}
I made it so that if the user puts more than 3 inputs, it will give a usage prompt. However, when I put in 2 inputs, I get an error instead of the usage prompt, even though 2 is not equal to 3.
Heres the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Accounting.main(Accounting.java:15)
How can I fix this?
EDIT: My issue here isn't that the part of the array is not there because there is only two inputs, but that it won't give the usage prompt.
The reason is because you try to access part of an array that doesn't exist:
String part3 = parts[2];
Where
parts.length == 2
I assume you get an index out of bounds error?