boolean finished = false;
while (!finished) {
System.out.println("Enter 'a' (add), 'm' (multiply), 'h' for max value or 'q' (quit) <");
char choice = scan.nextLine().charAt(0);
if (choice == 'a') {
System.out.println("Enter first operand value");
int first = scan.nextInt();
System.out.println("Enter second operand value");
int second = scan.nextInt();
System.out.println("Enter third operand value");
int third = scan.nextInt();
int m = add(first, second, third);
finished=false;
System.out.println(m);
}
if (choice == 'm') {
System.out.println("Enter first operand value");
int first = scan.nextInt();
System.out.println("Enter second operand value");
int second = scan.nextInt();
System.out.println("Enter third operand value");
int third = scan.nextInt();
int m = multiply(first, second, third);
finished=false;
System.out.println(m);
}
if (choice == 'h') {
System.out.println("Enter first operand value");
int first = scan.nextInt();
System.out.println("Enter second operand value");
int second = scan.nextInt();
System.out.println("Enter third operand value");
int third = scan.nextInt();
int m = max(first, second, third);
finished=false;
System.out.println(m);
}
if (choice =='q') {
finished = true;
}
I have this loop which word on the first iteration. However on the second iteration it fails. I get output like this:
Enter 'a' (add), 'm' (multiply), 'h' for max value or 'q' (quit) < a
Enter first operand value
5
Enter second operand value
5
Enter third operand value
5
15
Enter 'a' (add), 'm' (multiply), 'h' for max value or 'q' (quit) <
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:658)
Im new to java and I dont understand why its not working? Wouldn't the char choice variable reset each time the loop runs?
Aucun commentaire:
Enregistrer un commentaire