打电话时
next,应检查扫描仪是否有一个。
if(scan.hasNext()) scan.next();
根据Scanner#next的
Java文档
NoSuchElementException如果没有更多标记可用
您可以如下更改方法
private static int posNum(Scanner scan) { int input = 0; boolean error = false; if (scan.hasNext()) { if (scan.hasNextInt()) { input = scan.nextInt(); error = input <= 0; } else { scan.next(); error = true; } } while (error) { System.out.print("Invalid input. Please reenter: "); if (scan.hasNextInt()) { input = scan.nextInt(); error = input <= 0; } else { if (scan.hasNext()) scan.next(); error = true; } } return input;}
然后像下面这样称呼它
Scanner scan = new Scanner(System.in); int i = posNum(scan); System.out.println(i); int j = posNum(scan); System.out.println(j);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)