Java,扫描程序,输入不匹配异常

时间:2014-06-09 01:12:54

标签: java exception inputmismatchexception

这部分代码应该加载restoraunt的名称,然后菜单名称,然后菜单名称和价格但是当我运行它时,它接受所有的名称,然后当它最终达到价格时,我输入例如7.2并获得输入不匹配异常

  String newMenu = "";
  String newRestaurant = "";
  String[] newMenuItem = new String[10];
  double[] price = new double[10];
  int x = 0;  


       while (!(newMenu.equals("none"))) {
           System.out.println("What is the name of the Menu you wish to create (type 'none', if you are done):");
           newMenu = scan.next();
           if (newMenu.equals("none")) {
              System.out.println("Saving entry...");
              continue;

           } else {


              System.out.println("What is the name of the Menu item you wish to create (type 'none', if you are done):");
              newMenuItem[x] = "end";
              while (!(newMenuItem[x].equals("none"))) {
                 newMenuItem[x] = scan.next();

                 if (!(newMenuItem[x].equals("none"))) {
                    System.out.println("What is the price?");
                    price[x]= scan.nextDouble();
                    x++;


                    }    
                 }    
              }
           }

1 个答案:

答案 0 :(得分:0)

如果我了解您的程序输入,最简单的解决方案是在第79行和第80行之间添加类似的内容,

while (!scan.hasNextDouble()) {
  // The next token isn't a double.
  if (scan.hasNext()) {
    scan.next();
  } else { 
    System.err.println("Nothing to read");
    System.exit(1);
  }
}

因为,目前您的Scanner没有将下一个符号作为double