爲什麼我的代碼有一個運行時錯誤?(JAVA)與掃描儀
import java.util.Scanner;
public class StudentID
{
static int gradeLevel;
static int id;
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("---Student ID---");
System.out.print("Enter your first name: ");
String firstName = keyboard.next();
System.out.print("\nEnter your last name: ");
String lastName = keyboard.next();
System.out.print("\nEnter your grade level: ");
gradeLevel = keyboard.nextInt();
System.out.print("\nEnter your id: ");
id = keyboard.nextInt();
System.out.print("\nThe text for your student id is:");
String result = getIDText(firstName, lastName, gradeLevel, id);
System.out.print(result);
}
public static String getIDText(
String firstName,
String lastName,
int gradeLevel,
int id)
{
String result =
"\n\nName: " + lastName + ", " + firstName +
"\nGrade: " + gradeLevel +
"\nID: " + id;
return result;
}
}
我可以進入我的我的數據不錯,但在我的ID,然後按類型之後進入運行時錯誤,我的程序崩潰說我必須在id = keyboard.nextInt();
我錯誤的錯誤是這樣的:
java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
StudentID.main(StudentID.java:18)
這是什麼運行時錯誤? –
@JacekCz java.util.InputMismatchException \t在java.util.Scanner.throwFor(Scanner.java:864) \t在java.util.Scanner.next(Scanner.java:1485) \t在java.util.Scanner中.nextInt(Scanner.java:2117) \t在java.util.Scanner.nextInt(Scanner.java:2076) \t在StudentID.main(StudentID.java:18) –
所以錯誤代碼只是說,它無法解析什麼你輸入了一個整數。您的選擇是將輸入更改爲字符串,然後自己將其解析爲try catch塊。如果失敗,則要求用戶再次輸入該ID。 –