How to capture user input in Java or interact with user via command line
#1: Using the System.console( ) . This will not work within eclipse IDE. You can try it on a DOS or Unix command-line.
package com.user.input;
import java.io.Console;
public class Example1 {
public static void main(String[] args) {
Console console = System.console();
String input = console.readLine("What is your name:");
System.out.println("User input = " + input);
}
}
The output:
C:\temp>java -cp C:\Users\akumaras\workspace\test\bin com.user.input.Example1 What is your name:Arul User input = Arul C:\Users\akumaras\workspace\test\bin\com\user\input>
#2: The Scanner class.
package com.user.input;
import java.io.Console;
import java.util.Scanner;
public class Example2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter first operand?");
int operand1=reader.nextInt();
System.out.println("Enter second operand?");
int operand2=reader.nextInt();
System.out.println("The sum is: " + (operand1 + operand2));
}
}
The output:
Enter first operand? 5 Enter second operand? 6 The sum is: 11
#3: Decorating System.in with BufferedReader and SystemInputReader.
package com.user.input;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Example3 {
public static void main(String[] args) throws NumberFormatException, IOException {
//System.in is decorated with InputStreamReader and BufferedReader
//buffering is required for efficiency
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter first operand?");
int operand1 = Integer.parseInt(br.readLine());
System.out.println("Enter second operand?");
int operand2=Integer.parseInt(br.readLine());
System.out.println("The sum is: " + (operand1 + operand2));
}
}
The output:
package com.user.input;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Example3 {
public static void main(String[] args) throws NumberFormatException, IOException {
//System.in is decorated with InputStreamReader and BufferedReader
//buffering is required for efficiency
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter first operand?");
int operand1 = Integer.parseInt(br.readLine());
System.out.println("Enter second operand?");
int operand2=Integer.parseInt(br.readLine());
System.out.println("The sum is: " + (operand1 + operand2));
}
}
Note: You can also decorate it with DataInputStream. A good example of the decorator design pattern implemented in the Java I/O API.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home