Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading an "int" from a keyboard

 
Abder-Rahman Ali
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks.
 
Campbell Ritchie
Sheriff
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easiest way after Java5 is to create a Scanner object using System.in as a constructor argument and use its nextInt() method.
 
Norm Radder
Ranch Hand
Posts: 728
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic