2

My program contains a few options that the user can select via the input of a number which allows them to complete a specific task. Currently, my code is set up with if and else if loops to complete task if a certain number of input. However, at the minute the program terminates after one task. I want the user to be able to input another number to complete another task. I have tried surrounding the code with a while loop and an exit option to allow the user to escape the loop and end the program, but this is not working and results in a "java.util.NoSuchElementException". The program works fine without the while loop.

This is an example of the current code which hopefully conveys what I mean:

System.out.println("Enter one of the following commands:");
System.out.println("1 - something..");
System.out.println("2 - something else..");
System.out.println("3 - exit");
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choiceentry = scanchoice.nextInt();

while (choiceentry != 3) {

    if (choiceentry < 1 || choiceentry > 3) {

        System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
        choiceentry = scanchoice.nextInt();

    }

    else if(choiceentry == 1) {
        // ..do something
    }
    else if(choiceentry == 2) {
        //..something else
    }
    else if(choiceentry == 3) {
        //...exit program
    }

}   

So I want to get into this loop, and only exit to terminate the program. I'm hoping that the while loop would take the user back to a menu, allowing you to select another option, however this is not working. What is wrong with this code? And how can I implement this idea?

Thanks in advance!

1
  • 1
    It is not better to use switch ? Commented Dec 19, 2013 at 12:27

3 Answers 3

4

Use Scanner#hasNextInt() before you call Scanner.nextInt() to get rid of the NoSuchElementException

if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();

hasNextInt() returns true only if the next token is a valid int

You can do like this

    //set choiceentry to -1, this will make it to enter while loop
     int choiceentry = -1

    while(choiceentry < 1 || choiceentry > 3){

            System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
            if(scanchoice.hasNextInt())
            choiceentry = scanchoice.nextInt();

    }

     switch(choiceentry){
        case 1:
           //do logic
           break;
        case 2:
           //do logic
           break;
        case 3:
           //do logic
           break;
   }

I have changed it to use switch statements, since they come handy in getting input data

Sign up to request clarification or add additional context in comments.

2 Comments

I might be misunderstanding, but is there an extra brace in this code :/?
ha ha ha, closed the previous open brace (hidden).. Now, removed it :)
3

You are only asking the user to pick another menu item if choice is < 1 or > 3

you have to set this code in an else statement`:

while (choiceentry != 3) {
    else if(choiceentry == 1) {
        // ..do something
    }
    else if(choiceentry == 2) {
        //..something else
    }
    else if(choiceentry == 3) {
        //...exit program
    }
    else{

        System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
        choiceentry = scanchoice.nextInt();

    }

}   

Comments

1

If you want your program to continue prompting the user to select a task you'll need to move that prompt as well as your nextInt() call to somewhere inside your loop yet outside of an if statement so that it will always be invoked on each iteration.

As Mr Phi suggested in the comments, a switch statement would be a better alternative to your current if-else structure. It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values.

I'd also add that a do-while might be more suitable for this task. This way you won't need to code your prompt for a choice twice.

int choiceentry;

do {
    System.out.println("Enter \"1\", \"2\" or \"3\"");
    choiceentry = scanchoice.nextInt();

    switch (choiceentry)
    {
        case 1:
            // do something
            break;
        case 2: 
            // ..something else
            break;
        case 3: 
            // .. exit program
            break;
        default:
            System.out.println("Choice must be a value between 1 and 3.");
    }   
} while (choiceentry != 3);

3 Comments

I've tried to implement your suggestion but keep receiving a "Exception in thread "main" java.util.NoSuchElementException" at the for the statement "choiceentry = scanchoice.nextInt();" within the initial part of the do loop
It works for me but I'm not entirely sure how or why. You might need to wrap the call to nextInt() in an if-statement as suggested here. Don't forget to initialise choiceentry somewhere before the switch as well.
OK, so the code should work now, except I get an infinite loop of a case, I don't think the break statement is taking me back to the point where I can input a new value to execute the next "choice". EDIT: after looking at the loop the program goes through, the break is working and it is printing "Enter "1", "2" or "3"", but it is just accepting the old choice value and proceeding and not allowing the entry of a new one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.