我正在练习在java中使用方法,并制作了一个程序来计算两个数字(下面发布的代码)。
当用户收到此消息时,我的程序会出现java.lang.StringIndexOutOfBoundsException
错误:
Press 'y' to show the menu again or 'n' to terminate!
我知道如果我使用char again = input.next().charAt(0);
,该程序将正常工作!
但是,当用户甚至没有机会输入字符串时,为什么使用char again = input.nextLine().charAt(0);
会出错?
以下是完整代码:
import java.util.Scanner;
public class Test1 {
public static void menu (){
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("");
}
public static int add (int n1, int n2){
int result = n1 + n2;
return result;
}
public static int sub (int n1, int n2){
int result = n1 - n2;
return result;
}
public static int mul (int n1, int n2){
int result = n1 * n2;
return result;
}
public static void main (String[] args){
Scanner input = new Scanner (System.in);
int menu, reset = 0;
while (reset != 1){
do {
menu();
System.out.print("Choose from 1 ~ 3: ");
menu = input.nextInt();
} while( menu <= 0 || menu > 3);
System.out.print("Enter first number: ");
int n1 = input.nextInt();
System.out.print("Enter second number: ");
int n2 = input.nextInt();
switch (menu){
case 1: System.out.println("The addition of " + n1 + " + " + n2 + " is " + add(n1, n2)); break;
case 2: System.out.println("The subtraction of " + n1 + " - " + n2 + " is " + sub(n1, n2)); break;
case 3: System.out.println("The multiplication of " + n1 + " * " + n2 + " is " + mul(n1, n2)); break;
}
System.out.print("\nPress 'y' to show the menu again or 'n' to terminate!: ");
char again = input.nextLine().charAt(0); // here is the problem
if (again == 'y'){
reset = 0;
}
else if ( again == 'n'){
reset = 1;
System.out.println("BYE!");
}
else {
System.out.println("INVAILD INPUT!");
reset = 1;
System.exit(1);
}
}
}
}