2017-09-23 176 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(); 
}