
-----------------------------------
HeavenAgain
Mon Feb 26, 2007 8:15 pm

java user input
-----------------------------------
hi, I have a quick question on how to get user's input; byte, int, short, long, floating points too.
you see i use this In.class at school, but i really want to learn the things behind it.
would someone explain it to me quick? thanks :P

-----------------------------------
Aleks
Tue Feb 27, 2007 12:05 am

Re: java user input
-----------------------------------
You do not need any extra classes in your directory to get user input (for example, your in.class is unnecessary).  Some classes make it real easy, but Java already has a built in way of handling simple user input. 

This is a nice way of getting user input via command console type programs.  Of course I am assuming you just started Java 8-) 

At the beginning of your code type:

import java.io.*;

Then somewhere in your main method (before you take in any user input) add the line:

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));

To get input, simply add the line:

myVariable = userInput.readLine ();

However, doing this only yields a String as an input.  We must use a wrapper class if we are to get different types of input.  Here is how you do it.

// To read a double.
myDoubleVariable = Double.parseDouble(userInput.readLine());

// To read an integer.
myIntegerVariable = Integer.parseInt(userInput.readLine());

// etc.

And this my friend, is simple user input.  I hope it helped.  ^_^

-----------------------------------
klopyrev
Tue Feb 27, 2007 12:13 am

Re: java user input
-----------------------------------
I am going to explain how to read from Standard Input. If you want to use BufferedReader and other things like that, look at the post above mine. If you are talking about Standard Input, then System.in.read() is how you read input. It returns the next character. If you want to read an int, read everything until you get a space or an enter and then parse the input. The same for Byte, Float, etc. Use Integer.parseInt( ... ) or Double.parseDouble( ... ). If you have any more questions or I didn't explain everything, feel free to ask.

Example (This code will read an int from standard input. It doesn't take care of Errors and Exceptions):

String result="";
int ch = System.in.read();
while(ch>='0'&&ch