在java.util.Scanner.throwFor(未知源)错误

  private static int posNum() {

Scanner scan = new Scanner(System.in);

int input = 0;

boolean error;

if (scan.hasNextInt()) {

input = scan.nextInt();

error = input <= 0;

} else {

28 scan.next();

error = true;

}

while (error) {

System.out.print("Invalid input. Please reenter: ");

if (scan.hasNextInt()) {

input = scan.nextInt();

error = input <= 0;

} else {

scan.next();

error = true;

}

}

scan.close();

return input;

}

因此,第二次调用此方法将返回以下错误。

Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at q2.CylinderStats.posNum(CylinderStats.java:28)

at q2.CylinderStats.main(CylinderStats.java:62)

第一个调用rad = posNum();运行良好,然后第二个调用运行,height = posNum();不允许在错误发生之前输入值。

谢谢

回答:

打电话时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);

以上是 在java.util.Scanner.throwFor(未知源)错误 的全部内容, 来源链接: utcz.com/qa/427755.html

回到顶部