2017-09-23 175 views
-1

爲什麼我的代碼有一個運行時錯誤?(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) 
+2

這是什麼運行時錯誤? –

+0

@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) –

+0

所以錯誤代碼只是說,它無法解析什麼你輸入了一個整數。您的選擇是將輸入更改爲字符串,然後自己將其解析爲try catch塊。如果失敗,則要求用戶再次輸入該ID。 –

回答

1

代碼工作罰款如果您打印整數值爲ID。如果您打印String值,例如aaa,你得到這個java.util.InputMismatchException。如果你想檢查不正確的數據,你必須始終閱讀String然後在代碼手動轉換它。

P.S.你應該關閉Scanner isntance somehwere:不是keyboard.next 1.使用keyboard.nextLine()如果作爲輸入,才考慮你的字符串輸入中有空格之間:keyboard.close()

0

有兩種方法來解決這個直到它遇到第一個空間。如果你想使用keyboard.next 2.()只,檢查是否輸入的數據類型爲int,當你想爲e.g:

if(keyboard.hasNextInt()) 
{ 
    id = keyboard.nextInt(); 
}