3

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' 
Andrzej Doyle
  • 97,637
  • 30
  • 185
  • 225
Dani
  • 173
  • 3
  • 5
  • 20
  • 1
    Perhaps you could use readLine() instead of readByte() – Bob Flannigon Feb 14 '13 at 09:25
  • Why do you **not** expect the `while` loop to execute multiple times? That's the point of a loop, and yours will loop until `c == 'E'`. Since you didn't appear enter an E, this behaviour seems exactly as I would expect. It would be helpful to explain what alternative behaviour you were expecting. – Andrzej Doyle Feb 14 '13 at 09:26

6 Answers6

2

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);
wns349
  • 1,156
  • 1
  • 9
  • 19
  • Using charAt effectively trims the input to only including the first character, although in some cases putting "ty" should yield an error instead of returning 't'. Especially if both T and Y are valid choices, because the user could have hit both on accident but intended to write Y. – Steen Schütt Nov 14 '14 at 11:24
2

Use System.in.read() instead of DataInputStream.

Sumit Desai
  • 1,396
  • 8
  • 19
1

DataInputStream (InputStream) is fundamentally a binary construct. If you want to read text data (e.g. 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.

Jayamohan
  • 12,059
  • 2
  • 25
  • 39
1

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));
falsetru
  • 314,667
  • 49
  • 610
  • 551
Anurag
  • 11
  • 1
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

Community
  • 1
  • 1
0xA
  • 122
  • 1
  • 9
-1

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.

e.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' : y

VishalDevgire
  • 3,854
  • 6
  • 27
  • 56