0

Here it only executes one time and then gives the error given below. Please help in solving this problem that I'm

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");
   }
}

Output: (Getting an Exception 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 Answers1

1

Change your code as follows:

  • Change String y to char y

  • And read the char with y = sc.next().charAt(0) instead of nextLine()

Hope it works

dubka
  • 11
  • 2