Accepting Keyboard Input

First of all we need to know that in java for printing the line we use following command:

System.out.println();
While we code the System then it is related with input and output and all the hardware conf.
Then the keyword out defines about the display of the line.
Now we need to input instead of output.
So just code by following ways:
System.in.read();

In this code the in defines the input of keyboard and the read means the input data is read by the java compiler.The InputStream class provides a primary function called read so this can read only a character at a time.
A sample class for input data:

In class SystemInExample:

[sourcecode=’java’]
import java.io.*;

public class SystemInExample {

//CONSTRUCTOR
public SystemInExample(){}

//a static method which perform input funtion throws IOException
public static String getInput()throws IOException{
StringBuffer strBuff = new StringBuffer();

//exception handler
try{
char input = (char)System.in.read();
while(input != ‘n’){
strBuff.append(input);
input = (char)System.in.read();
}

}

//IO Exception handler
catch(IOException a){
System.out.println(“Invalid”);
}

//returns a string value
return strBuff.toString().trim();
}
}

[/sourcecode]

In class InvokeInput
[sourcecode=’java’]
//importing java io package
import java.io.*;

public class InvokeInput {
//CONSTRUCTOR
public InvokeInput() { }

//a main method to invoke the input code
//this method throws and IOException
public static void main(String[] args)throws IOException{

System.out.print(“Please enter your Name: “);
String invoke = SystemInExample.getInput();
System.out.println(“Hello ” + invoke);

}

}

[/sourcecode]

Output:

output

For any confusion please comment me:

Leave a Reply