Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why?! 1

Status
Not open for further replies.

creso

Programmer
Jul 14, 2002
2
IN
Hi,

Consider the following program:

try {
int choice = 0;
while (choice != 5) {
System.out.println(" 1 : push a onto b ");
System.out.println(" 2 : push a over b ");
System.out.println(" 3 : stack a onto b ");
System.out.println(" 4 : stack a over b ");
System.out.println(" 5 : quit ");
choice = System.in.read();
System.out.println("choice :" + choice);
}
} catch (Exception e) {
System.out.println(" Error : " + e.getMessage());
}

The program accepts a number from the user, prints the entered number, and displays the menu again. Instead of the entered number being printed 3 new numbers are getting printed (with the menu)!! For example, if I enter 3, I get 51, (menu), 13, (menu), 10 !! Can anyone tell me why this is happening?

Regards.
 
You are reading in the character from the user and performing an implicit cast from a char to an int. This just gives you the unicode value of the char not the int value. In other words, if someone enters a four you are getting a '4' not a 4. Understand?

You also should wrap your input stream with a BufferedReader and take in the input line by line instead of a character at a time.

 
Hi,

Thanks for reply... I actually had the following line of code:

choice = Integer.parseInt(System.in.read());

I thought, the above would convert "character" to "int". But, the output was as follows:

1 : push a onto b
2 : push a over b
3 : stack a onto b
4 : stack a over b
5 : quit
1
choice :49
1 : push a onto b
2 : push a over b
3 : stack a onto b
4 : stack a over b
5 : quit
choice :13
1 : push a onto b
2 : push a over b
3 : stack a onto b
4 : stack a over b
5 : quit
choice :10
1 : push a onto b
2 : push a over b
3 : stack a onto b
4 : stack a over b
5 : quit

My doubt is, how is that the loop is automatically printing the "menu options" 3 times?! (I assume 13 & 10 are carriage return & new line)

Your suggestion of using InputStreamReader, BufferedReader & readLine worked out... thanks... (I still have the above doubt !!)

Regards
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top