收到下面提到的程序的“线程”main“java.util.NoSuchElementException中的异常”错误 [duplicate]

Getting an "Exception in thread "main" java.util.NoSuchElementException" error for the program mentioned below [duplicate]

提问人:Amit Singh 提问时间:1/23/2021 最后编辑:Amit Singh 更新时间:1/23/2021 访问量:129

问:

在这里,它只执行一次,然后给出下面给出的错误。 请帮助解决我遇到的这个问题

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)
java.util.scanner 执行

评论

0赞 Aalexander 1/23/2021
比较字符串时,请使用 .equals()

答:

1赞 dubka 1/23/2021 #1

按如下方式更改代码:

  • 更改为String ychar y

  • 并读取字符,而不是y = sc.next().charAt(0)nextLine()

希望它有效

评论

0赞 Federico klez Culloca 1/23/2021
并将whilewhile(y == 'Y' || y == 'y')