Steven Sharman
Steven Sharman

Reputation: 251

Java Char Empty Character Detection

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?

Upvotes: 0

Views: 1253

Answers (3)

brso05
brso05

Reputation: 13222

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.

Upvotes: 1

Kartic
Kartic

Reputation: 2985

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

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

Upvotes: 0

couettos
couettos

Reputation: 591

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');

Upvotes: 2

Related Questions