提问人:Amit Singh 提问时间:1/23/2021 最后编辑:Amit Singh 更新时间:1/23/2021 访问量:129
收到下面提到的程序的“线程”main“java.util.NoSuchElementException中的异常”错误 [duplicate]
Getting an "Exception in thread "main" java.util.NoSuchElementException" error for the program mentioned below [duplicate]
问:
在这里,它只执行一次,然后给出下面给出的错误。 请帮助解决我遇到的这个问题
package project1;
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
String y;
do {
Scanner sc = new Scanner(System.in);
int flag = 1;
System.out.println("Print the number:");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
flag *= i;
}
System.out.println(flag);
System.out.println("Press Y/y to continue");
y = sc.nextLine();
sc.close();
} while(y == "Y" || y == "y");
}
}
输出:(获取异常 java.util.NoSuchElementException)
Print the number:
12
479001600
Press Y/y to continue
y
Print the number:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at project1.factorial.main(factorial.java:14)
答:
1赞
dubka
1/23/2021
#1
按如下方式更改代码:
更改为
String y
char y
并读取字符,而不是
y = sc.next().charAt(0)
nextLine()
希望它有效
评论
0赞
Federico klez Culloca
1/23/2021
并将while
while(y == 'Y' || y == 'y')
评论