Home > Enterprise >  Stuck in a do...while loop in Java
Stuck in a do...while loop in Java

Time:11-20

Here's my code:

do{
    sc.nextLine();
    System.out.println("What kind of operation do you want to do?");
    String res=sc.nextLine();
    switch(res){
           //cases
           default:System.out.println("Invalid input");
    }
    System.out.print("Do you want to do any other operation? 1/0...");
    ans=sc.nextShort();
}while(ans==1);

Whenever I try to execute the block, the first operation is doing good but then when I enter 1 to do some other operation, I am not being asked 'what kind of operation you want to do' and it is directly showing 'Invalid input'.

CodePudding user response:

This is a known issue with Scanner. I do not know the details, but when you read a number like scan.nextInt() and then you want to read a string like scan.next() you should do scan.nextLine() between to switch a context or smth. in the Scanner.

Scanner scan = new Scanner(System.in);
int ans;

do {
    System.out.print("What kind of operation do you want to do? ");
    String res = scan.nextLine();

    switch (res) {
        //cases
        default:
            System.out.println("Invalid input");
    }

    System.out.print("Do you want to do any other operation (0/1)? ");
    ans = scan.nextInt();
    scan.nextLine();    // after reading a number you have to do this to be able to read a string next
} while (ans == 1);

CodePudding user response:

I have seen different issues with different IDEs' consoles regarding Scanner. What I do is always read using scanner.nextLine() and parse it to required type. This way we can also validate the input and show a user friendly error, rather than Scanner throwing an exception when it was expecting nextInt() and got something else.

  • Related