NumberFormatException on Integer input after previous Long input
NumberFormatException on Integer input after previous Long input
我在之前调用 Long
输入后调用 Integer
输入时收到 NumberFormatException
。下面是我的代码片段
System.out.print("Student ID: ");
studentID = sc.nextLong();
System.out.print("Student Number: ");
studName= Integer.parseInt(sc.nextLine());
错误输出如下
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Student Name: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at student.StudentClient.main(StudentClient.java:68)
Java Result: 1
我可以知道如何解决这个错误吗?
我改用 sc.nextInt()
。但是,在我的代码开头:
System.out.println("\nMENU 1-QUIT / 2-ADD STUDENT");
option = option = sc.nextInt();
if (option == 1) {
System.exit(0);
}
if (option == 2) {
studentIndex++;
studentList[studentIndex] = new Student();
System.out.print("Student Title (Mr/Mrs): ");
studentTitle = sc.nextLine();
System.out.print("Student First Name: ");
firstName = sc.nextLine();
上述代码的输出跳过了 1x 输入。这使得它:
Student Title: Student First Name:
您的问题是对 nextLong() 的调用会读取下一个长数字,但不会读取其后的换行符。因此,当您调用下一行时,您会返回从您刚刚阅读的数字末尾到换行符的空白行。例如,如果我这样做:
System.out.println("'" + sc.nextLong() + "'");
System.out.println("'" + sc.nextLine() + "'");
System.out.println("'" + sc.nextLine() + "'");
... 并输入数字,如 42 和 63 我将得到打印:
'42'
''
'63'
您需要始终使用 nextLong() 或 nextLine(),但不要混用。
我在之前调用 Long
输入后调用 Integer
输入时收到 NumberFormatException
。下面是我的代码片段
System.out.print("Student ID: ");
studentID = sc.nextLong();
System.out.print("Student Number: ");
studName= Integer.parseInt(sc.nextLine());
错误输出如下
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Student Name: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at student.StudentClient.main(StudentClient.java:68)
Java Result: 1
我可以知道如何解决这个错误吗?
我改用 sc.nextInt()
。但是,在我的代码开头:
System.out.println("\nMENU 1-QUIT / 2-ADD STUDENT");
option = option = sc.nextInt();
if (option == 1) {
System.exit(0);
}
if (option == 2) {
studentIndex++;
studentList[studentIndex] = new Student();
System.out.print("Student Title (Mr/Mrs): ");
studentTitle = sc.nextLine();
System.out.print("Student First Name: ");
firstName = sc.nextLine();
上述代码的输出跳过了 1x 输入。这使得它:
Student Title: Student First Name:
您的问题是对 nextLong() 的调用会读取下一个长数字,但不会读取其后的换行符。因此,当您调用下一行时,您会返回从您刚刚阅读的数字末尾到换行符的空白行。例如,如果我这样做:
System.out.println("'" + sc.nextLong() + "'");
System.out.println("'" + sc.nextLine() + "'");
System.out.println("'" + sc.nextLine() + "'");
... 并输入数字,如 42 和 63 我将得到打印:
'42'
''
'63'
您需要始终使用 nextLong() 或 nextLine(),但不要混用。