Command Line Input in Java
So far we have been using only the Command Line Ouput System.out.println to display and message on console. Java also has a method for console input.
We will now show how to get Console Input.
/*
ReferenceDesigner.com Java Tutorial
Understanding Console Input InputStreamReader
*/
import java.io.BufferedReader ;
import java.io.IOException ;
import java.io.InputStreamReader ;
class readname {
public static void main( String [ ] args) {
System .out .print ( "What is your name : " ) ;
try {
BufferedReader bufferRead = new BufferedReader ( new InputStreamReader ( System .in ) ) ;
String name = bufferRead.readLine ( ) ;
System .out .println ( ) ;
System .out .println ( "Hello " + name) ;
}
catch ( IOException e)
{
e.printStackTrace ( ) ;
}
}
}
If you compile and run, it prompts you and awaits for your response. Once you enter a complete line It responds back with hi
yourname
What is your name : Michael
Hello Michael