CS 1063, Fall 2005
|
In case your version of JBuilder is using the 1.5 version of Java, you can use the following code to input an integer:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type an integer and then 'Return' ---> ");
int quantity = in.nextInt();
System.out.println("You typed: " + quantity);
}
}
Results of a run (boldface = typed input):
Type an integer and then 'Return' ---> 314159
You typed: 314159
If you don't have version 1.5 on your computer, or if you can't seem to configure JBuilder to work with 1.5, you can use the following approaches, which work with older versions of Java. In the following, the blue code above has been replaced with red below. It's a little more complicated, but you just have to copy the "magic" commands.
import java.io.*;
public class BufferedReaderTest {
public static void main(String[] args) throws IOException {
BufferedReader in =
new BufferedReader( new InputStreamReader(System.in));
System.out.print("Type an integer and then 'Return' ---> ");
String input = in.readLine();
int quantity = Integer.parseInt(input);
System.out.println("You typed: " + quantity);
}
}
In case you want to read numbers somewhere besides the main method, you would need to have the phrase throws IOException on every method from main down to where you are doing the input. This can be annoying, so instead you can use the following code anywhere, even buried inside a private method. As before, the blue code at the beginning has been replaced with red below.
import java.io.*;
public class BufferedReaderTest2 {
public static void main(String[] args) {
BufferedReader in =
new BufferedReader( new InputStreamReader(System.in));
System.out.print("Type an integer and then 'Return' ---> ");
String input = "";
try {
input = in.readLine();
} catch (IOException e) {
System.out.println("Exception reading character");
}
int quantity = Integer.parseInt(input);
System.out.println("You typed: " + quantity);
}
}