We note here that System.in gets the stream from primary input devices such as keyboard.
1) Using Scanner Object
// prompt the user to enter their name
System.out.print(“Enter your name: “);
// get their input
Scanner scanner = new Scanner(System.in);
// there are several ways to get the input, this is
// just one approach
String username = scanner.nextLine();
//Display name
System.out.println(“Your Name is:”+username);
2) Using BufferedReader Object
// prompt the user to enter their name
System.out.print(“Enter your name: “);
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the username from the command-line; need to use try/catch with the
// readLine() method
String userName = br.readLine();
//Display Name
System.out.println(“Your Name is:”+userName);
The above mentioned code is quite straightforward and its your choice which method to use.
Thanks for your effort to read my article.
Here are some useful methods we can directly use in applications:
// to get string
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
// to get a character
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//to get integer
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}