简体   繁体   中英

How to take single character input from user in Java?

In the below example , I am trying accept single character input from user, but when running the program, I get do..while loop executed multiple times. Please see the result of the program below.

If some one could help me with the answer, how to fix this problem?

import java.io.*;



public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {



            char c;
           // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            DataInputStream in =new DataInputStream(System.in);

            // Asking the user what to do with the application
           do{ 

            System.out.println("Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' ");          

            byte b = in.readByte();
            c = (char) b;
            c = Character.toUpperCase(c);

            if (c=='Y'){
                System.out.println(c);
               }
            else if (c=='N') {
              System.out.println(c);
            }
            else if (c=='E'){
               System.out.println(c); 
            }
            else{
                System.out.println("Incorrect Entry, try again: "+c); 
            }

           }while (c!='E');

    }

}

Output

init:
deps-jar:
compile:
run:
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
asdfgaf
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: S
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: D
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: G
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 
Incorrect Entry, try again: 

Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' 

Using DataInputStream isn't probably the best way to handle your situation.

DataInputStream buffers the inputs that you typed, which is why you get unwanted lengthy messages with loops.

Try using Scanner instead. Here's an example of Scanner:

Scanner objScanner = new Scanner(System.in);
char c = objScanner.next().charAt(0);
System.out.println(c);

使用System.in.read()而不是DataInputStream。

DataInputStream ( InputStream ) is fundamentally a binary construct. If you want to read text data (eg from the console) you should use a Reader. In the source code There was a commented out BufferedReader . Its better to use the same instead of DataInputStream . You can do as below,

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = in.readLine();

Or you can use DataInputStream.readLine() , but its deprecated for a reason. And its suggested there also to use BufferedReader.readLine() .

You can go for other options like Scanner .

User Scanner class for getting input. Its good way to resolve your issue.

Scanner scan = new Scanner(System.in);
System.out.println(scan.next().charAt(0));

Since this thread has no ACCEPTED ANSWER yet, I'm still going to answer even though its really old; for the people who still want a explanation.

Using a Scanner are the best idea for the situation. Scanners are easy to use, and stop the thread until completion. You can use this to your advantage, or you can create a new thread to keep the current thread running. The basic usage of a scanner:

Scanner s = new Scanner(System.in) //Makes a new scanner with System.in
String letter = s.next(); //Use next to find the character typed
//Insert code using letter variable

"letter" will return EVERYTHING before a space in the scanner. To only find the first letter, split the string by "" then take the 1st (0th) of the array.

Lastly, a good quote taken from this thread about scanners

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \\n). Once the input is read, nextLine() positions the cursor in the next line.

Later, when looking for multiple words, use nextLine() instead of next() to get the full String

Probably in above execution example you gave input as "asdfgaf" and then pressed enter. hence it is taking A, S, D, F .... as input one character at a time. you should give input as 'y' or 'n' or 'e' (single character at a time) and then press Enter.

eg Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' : y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM