CS118: Programming for Computer Scientists
One example of text-based input and output
An example of text-based input and output follows. Each text book provides its
own method for dealing with this, and there is no single way of doing it.
import java.io.*;
public class ReadStuff {
public static void main(String[] args) throws IOException {
// Create input stream in using stdin.
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// String to store user's input
String userInput;
// Give a prompt
System.out.print("Enter a string: ");
// Read a line of input
userInput = in.readLine();
// Check it worked
System.out.println("You typed: " + userInput);
// Now read an int (using Integer to convert between String and int)
// to store user's input. Classes Double, Float and Long allow
// conversion between conversion between String and double etc.
System.out.print("Enter an integer: ");
userInput = in.readLine();
Integer y = new Integer(userInput);
int x = y.intValue();
// Check it worked
System.out.println("Your integer was: " + x);
}
}