Basic Calculator

import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
// Your Code Here
boolean flag=true;
do {
Scanner s=new Scanner(System.in);

	char n = s.next().charAt(0);
	
	switch(n) {
	case '+':
		int num1=s.nextInt();
		int num2=s.nextInt();
		System.out.println(num1+num2);
		break;
	case '-':
		num1=s.nextInt();
		num2=s.nextInt();
		System.out.println(num1-num2);
		break;
	case '*':
		num1=s.nextInt();
		num2=s.nextInt();
		System.out.println(num1*num2);
		break;
	case '/':
		num1=s.nextInt();
		num2=s.nextInt();
		System.out.println(num1/num2);
		break;
	case '%':
		num1=s.nextInt();
		num2=s.nextInt();
		System.out.println(num1%num2);
		break;
	case 'x':
		flag=false;
		break;
	case 'X':
		flag=false;
		break;
	default :{
		System.out.println("Invalid operation. Try again.");
		break;
	}

	}
	
}while(flag==true);

}

}

Error is :
Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Main.main(Main.java:9)

Why this error occur? How can I resolve it

@ankitsharma11072002 bench mark your code with this code and you will see your mistake
and also don’t initialise your scanner inside the do while loop . initialise it outside the loop.

import java.util.Scanner;
public class main{
   static Scanner scn=new Scanner(System.in);
    public static void main(String[] args) {
        char ch;
        do {
            ch = scn.next().charAt(0);  // Use cin in case of c++
            if (ch == '+' || ch == '-' || ch == ' * ' || ch == '/' || ch == '%') {
                operation(ch);
            } else {
                if (ch != 'x' && ch != 'X')
                    System.out.println("Invalid operation. Try again.");
            }
        } while (ch != 'x' && ch != 'X');
    }
    public static void operation(char ch) {
        int a = scn.nextInt(); // Use cin in case of c++
        int b = scn.nextInt(); // Use cin in case of c++
        int res = 0;
        switch (ch) {
        case '+': {
            res = a + b;
            break;
        }
        case '-': {
            res = a - b;
            break;
        }
        case '*': {
            res = a * b;
            break;
        }
        case '/': {
            res = a / b;
            break;
        }
        case '%': {
            res = a % b;
            break;
        }
        }
        System.out.println(res);
    }
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.