2017-02-17 80 views
0

我遇到了Scanner问题,因为它似乎正在接受输入值类型,并强制下次用户输入的值为相同类型。我无法找到任何原因,为什么这段代码不工作,并给我一个InputMismatchException,因为我写了这样的代码一百万次,没有问题。找不到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(); 
    } 

此问题是不只是为寄存器()方法,但计划范围,例如具有这样的代码:

public void Options() { 
    Scanner input=new Scanner(System.in); 
    while (true) { 
     System.out.println("What would you like to do (Enter corresponding number):" + "\n" + "1) View all courses" + "\n" + "2) View all courses that are not full" + "\n" + "3) Register on a course" + "\n" + "4) Withdraw from a course" + "\n" + "5) View all courses that the current student is being registered in" + "\n" + "6) Exit"); 
     int user = input.nextInt(); 
     if (user == 1) 
      viewAll(); 
     if (user == 2) 
      viewAllOpen(); 
     if (user == 3) 
      register(); 
     if (user == 4) 
      withdraw(); 
     if (user == 5) 
      viewRegistered(); 
     if (user == 6) { 
      Serialize(); 
      break; 
     } 
    } 

如果的方法中,如寄存器中的一个需要用户输入一个String,int user = input.nextInt();将导致InputMismatchException。

+1

检查http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – TheLostMind

回答

0

我已经转载了这段代码,并没有遇到同样的问题。如果用户在提示输入课程编号时输入一个整数(如11),则代码将正常运行。当然,如果你输入的不是整数,它会抛出一个InputMismatchException。扫描程序#nextInt()的Java文档描述,具体如下:

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

形式nextInt的这种方法(的调用)的行为以完全相同的方式调用nextInt(基数),其中基数是此扫描器的默认基数。

抛出:

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

Read More

如果要避免这种情况,不想为了处理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); 
} 
+0

这不是没有输入整数的问题。当我运行它,我甚至不获得为InputMismatchException时后我输入我想为注册课程的名称出现,然后程序停止,进入一个整数的机会。 – UnionSquareBanter

+0

尽快在您扫描所请求的字符串后,在Options方法中关闭扫描仪。该资源仍处于打开状态的事实。我对扫描仪的注册方法被打开干扰。如果这不起作用,然后粘贴你的堆栈跟踪。 '扫描仪输入=新扫描仪(System.in); 而(真){ 的System.out.println( “等等”); int user = input.nextInt(); input.close() //其他代码here.' –