Skip to content
February 22, 2009 / Narayan

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:

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();
}
}

In class InvokeInput

//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);
}

}

Output:

output

For any confusion please comment me:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: