Java扫描仪:scanner.hasNextInt()无法正常工作

时间:2019-06-08 09:12:37

标签: java input int java.util.scanner

我正在为我的高中做一个简单的项目,但是遇到了问题。 问题是我正在尝试使用扫描仪获取输入并检查它是否为int。但是扫描仪无法正常工作。同时,我想根据用户输入运行一个循环,因此我需要另一台扫描仪。

我在线上搜索过,找不到真正的解决方案。我添加了另一台扫描仪,但这是一个临时解决方案,不能像适当的扫描仪那样工作。

System.out.println("please enter a coordinate for X between 1 and " + (forest.getForest().length - 2
  + " if you pick an invalid coordinate a random one will be selected, however it may not have a tree there"));
if (scan.hasNextInt() == false) {
  System.out.println("the coordinate you entered is invalid a random one is being generated");
  x = (int) Math.random() * (forest.getForest().length - 3) + 1;
} else {
  x = scan.nextInt();
  if (x < 1 || x > forest.getForest().length - 2) {
    System.out.println("the coordinate you entered is invalid a random one is being generated");
    x = (int) Math.random() * (forest.getForest().length - 3) + 1;
  }
}

System.out.println("please enter a coordinate for Y between 1 and " + (forest.getForest().length - 2
  + " if you pick an invalid coordinate a random one will be selected, however it may not have a tree there"));
if (scan2.hasNextInt() == false) {
  System.out.println("the coordinate you entered is invalid a random one is being generated");
  y = (int) Math.random() * (forest.getForest().length - 3) + 1;
} else {
  y = scan2.nextInt();
  if (y < 1 || y > forest.getForest().length - 2) {
    System.out.println("the coordinate you entered is invalid a random one is being generated");
    y = (int) Math.random() * (forest.getForest().length - 3) + 1;
  }
}

这是使用扫描仪的代码部分,但是当我尝试获取其他输入时,它不起作用。我没有收到任何错误,但它不接受任何输入。

0 个答案:

没有答案