This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Reading an Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading an "int" from a keyboard" Watch "Reading an "int" from a keyboard" New topic

Reading an "int" from a keyboard

Abder-Rahman Ali
Ranch Hand

Joined: May 22, 2008
Posts: 138
How canI read an "int" value from a keyboard, such that I want after that compare if the entered "int" is what I want?

For example, if I want the user to enter the int value "1", and after that I want to make a switch statement to check if the entered integer is "1" or not?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45421
Easiest way after Java5 is to create a Scanner object using as a constructor argument and use its nextInt() method.
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 691
You enter char values from a keyboard. The "1" key will pass a char '1' to your input code. A char takes 2 bytes(as Unicode) to store its value. In ASCII it took just one byte. Looking at its value in different ways: the char "1"'s value is 00110001 in binary, 0x31 in hex, and 49 as int. Those are 3 different ways of looking at the same value in memory.

If you cast a char to int you will see this.
It is not easy to enter an int value of 1 via a keyboard.
I agree. Here's the link:
subject: Reading an "int" from a keyboard
It's not a secret anymore!