Java 找不到输入不匹配异常的原因

Java 找不到输入不匹配异常的原因,java,java.util.scanner,inputmismatchexception,Java,Java.util.scanner,Inputmismatchexception,我对Scanner有一个问题,它似乎采用了输入值类型,并强制用户下次输入相同类型的值。我找不到这段代码不起作用的任何原因,并给了我一个InputMismatchException,因为我已经编写了一百万次这样的代码,并且没有遇到任何问题 public void register(){ Scanner input=new Scanner(System.in); System.out.println("What course would you like to regist

我对Scanner有一个问题,它似乎采用了输入值类型,并强制用户下次输入相同类型的值。我找不到这段代码不起作用的任何原因,并给了我一个InputMismatchException,因为我已经编写了一百万次这样的代码,并且没有遇到任何问题

 public void register(){
    Scanner input=new Scanner(System.in);
        System.out.println("What course would you like to register for?");
        String course_name = input.next();
        System.out.println("What section?");
        int section = input.nextInt();

        for (int i = 0; i < courses.size(); i++) {
            if (courses.get(i).getCourse_name().equals(course_name)) {
                if (courses.get(i).getCourse_section() == section) {
                    courses.get(i).AddStudent(this.first_name+" "+this.last_name);
                }
            }
        }
        input.close();
    }

如果其中一个方法(如register)要求用户输入字符串,则int user=input.nextInt();将导致输入不匹配异常

我已经复制了这段代码,我没有同样的问题。如果用户在提示输入课程号时输入整数(如11),代码将正常运行。当然,如果您输入的内容不是整数,它将抛出InputMismatchException。请参阅Scanner#nextInt()的Java文档说明,特别是:

将输入的下一个标记扫描为int

此方法的调用形式为nextInt(),其行为方式与调用nextInt(基数)完全相同,其中基数是此扫描程序的默认基数

抛出:

InputMismatchException-如果下一个标记与整数正则表达式不匹配,或超出范围

如果您想防止这种情况发生,并且不想处理try-catch,可以暂停执行,直到给出一个有效的整数

public static void register(){
    Scanner input=new Scanner(System.in);
    System.out.println("What course would you like to register for?");
    String course_name = input.next();
    System.out.println("What section?");
    //Loop until the next value is a valid integer.
    while(!input.hasNextInt()){
        input.next();
        System.out.println("Invalid class number! Please enter an Integer.");
    }
    int section = input.nextInt();
    input.close();
        
    System.out.println(course_name + " " + section);
}

检查这不是一个不输入整数的问题。当我运行它时,我甚至没有机会输入一个整数,因为在我输入我想注册的课程名称后,InputMismatchException会立即发生,并且程序停止。在获得扫描请求的字符串后,请尝试用Options方法关闭扫描程序。资源仍处于打开状态这一事实会干扰在register方法中打开的扫描仪。如果这不起作用,那么粘贴堆栈跟踪<代码>扫描仪输入=新扫描仪(System.in);while(true){System.out.println(“blah”);int user=input.nextInt();input.close()//此处的其他代码。
public static void register(){
    Scanner input=new Scanner(System.in);
    System.out.println("What course would you like to register for?");
    String course_name = input.next();
    System.out.println("What section?");
    //Loop until the next value is a valid integer.
    while(!input.hasNextInt()){
        input.next();
        System.out.println("Invalid class number! Please enter an Integer.");
    }
    int section = input.nextInt();
    input.close();
        
    System.out.println(course_name + " " + section);
}