1

It works fine with '1'but with the other options it runs 3x times (by printing out the whole Menu thing before allowing user input again.

char a; 
    
    do { 
    System.out.println ("MENU");
    System.out.println ("Press 1 to EXIT");
    System.out.println ("Press 2 to PLAY");
    System.out.println ("Press 3 for SETTINGS");
    a = (char)System.in.read();
    switch (a){
    
    case '1': 
        System.out.println ("You have EXITED");
        break;
    case '2':
        System.out.println ("GAME OVER");
        break;
    case '3':
        System.out.println ("You chose SETTINGS");
        break;
    }
    
    }while (a != '1');




    
DaleNixon
  • 11
  • 1

2 Answers2

1

By default the console (or similar) is line buffered, so you type a digit followed by return/enter. You are reading a character at a time. The three characters you see are the digit, Carriage Return (CR/'\r') and New Line (NL/'\n').

See this question How to read a single char from the console in Java (as the user types it)? Alternatively read a line at a time - most example programs will use java.util.Scanner.

Tom Hawtin - tackline
  • 139,906
  • 30
  • 206
  • 293
0

You have to reset the a as '1'. The reason it was executing repeatedly is because the value of as is not reset

Dina
  • 41
  • 3