扫描程序的运行时错误

时间:2017-09-23 20:00:43

标签: java

为什么我的代码有运行时错误?(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 :(得分:1)

如果您为 ID 打印整数值,则代码可以正常工作。如果您打印String值,例如aaa,您得到此java.util.InputMismatchException。如果您想检查不正确的数据,则必须始终阅读String,然后在代码中手动转换它。

P.S。 您应关闭Scanner isntance somehwere:keyboard.close()

答案 1 :(得分:0)

有两种解决方法: 1.如果您的字符串输入之间有空格,则使用keyboard.nextLine()而不是keyboard.next,因为只有在遇到第一个空格时才会考虑输入。 2.如果你只想使用keyboard.next(),请检查输入是否为int,例如:

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