0

Right so im using java on eclipse and kept coming up with a problem. What im trying to fix is when the user is promoted to press any key. When the key is enter and no Char the program collapses due to it can't find a character.

my code is:

Scanner scan = new Scanner(System.in);
    Game game = new Game();
    char quit=' ';

    while (quit != 'N') 
    {
        game.play();

        System.out.println("Play again? Press any key to continue, or 'N' to quit");
        quit = scan.nextLine().toUpperCase().charAt(0);

    }

When ever enter is pressed, it stops the program due to no characters inputted. Is there a way around this and let the program continue when enter is pressed?

3 Answers 3

2

I would write it like this :

    Scanner scan = new Scanner(System.in);
    String line;

    do{
        game.play();
        System.out.println("Play again? Press any key to continue, or 'N' to quit");
        line = scan.nextLine();

    }while (line.isEmpty() || line.toUpperCase().charAt(0) != 'N');
Sign up to request clarification or add additional context in comments.

Comments

1

You can check the length:

while (quit != 'N') 
{
    game.play();

    System.out.println("Play again? Press any key to continue, or 'N' to quit");
    String test = scan.nextLine().toUpperCase();
    if(test != null && test.length() > 0)
    {
       quit = test.toUpperCase().charAt(0);
    }
    else
    {
         //handle your else here
         quit = ' '; //this will keep it from terminating
    }
}

Store the next line in a string then check to make sure it is not null and its length is at least 1. If so then get the first char. If not then decide how you want to handle that situation.

3 Comments

Ok thanks @brso05 ive added that just trying to stop program terminating now :D
@StevenSharman you can set quit = ' ' in your else if you don't want it to terminate...
@brso05 Ok thanks, I also found couettos to work as well but I will recommend both
0

Instead of quit = scan.nextLine().toUpperCase().charAt(0);, we can write:

String str = scan.nextLine().toUpperCase();
quit = ((str == null || "".equals(str)) ? ' ' : str.charAt(0));

Comments

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.