Discussion Locked

int from java.lang.System.in

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I am learning java an I just want to get an int from the console. I seem to only find a reliable way to get a byte. I can't even get a char[] very reliably either. Does anyone have a suggestion on how the get an int from the user using System.in?

3 replies

by bayard-generationjava

This is a common problem. The main answer is that you can read a String in by putting a BufferedReader around an InputStreamReader around STDIN. So:

new BufferedReader( new InputStreamReader( System.in ) );

then call readLine() on the bufferedreader.

This allows you to read a line at a time in from STDIN as a String.

Now, as for the int part. The following is not an int: 33

It is a String made up of some numerical characters. That is all you type on the command line. You can'ttype int's directly from the keyboard. So your code that is reading strings in then needs to convert them to numbers. Look at java.lang.Integer for methods to do that. parseInt and valueOf probably.

by tekkalan

You took a different approach. There does not seem to be an easy method like cin << someIntVariable; Here is the code I eventually got to work. I hope this will help anyone else running into this problem.
public static int getInt() throws IOException
{
int temp;
byte buffer[] = new byte[30];
System.in.read(buffer);
String tempStr = (new String(buffer)).trim();
temp = Integer.parseInt(tempStr);
return temp;
}

This discussion is closed to new replies.