You can obtain input from an input dialog box using the JOptionPane.showInputDialog method. Alternatively, you may obtain input from the console.
Java uses System.out to refer to the standard output device, and System.in to the standard input device. By default the output device is the console, and the input device is the keyboard. To perform console output, you simply use the println method to display a primitive value or a string to the console. Console input is not directly supported in Java, but you can use the Scanner class to create an object to read input from System.in , as follows :
Scanner scanner = new Scanner(System.in);
Scanner is a new class in JDK 1.5. The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner scanner declares that scanner is a variable whose type is Scanner . The whole line Scanner scanner = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable scanner . An object may contain methods . Invoking a method on an object is to ask the object to perform a task. A Scanner object contains the following methods for reading an input:
next () : reading a string. A string is delimited by spaces.
nextByte() : reading an integer of the byte type.
nextShort() : reading an integer of the short type.
nextInt() : reading an integer of the int type.
nextLong() : reading an integer of the long type.
nextFloat() : reading a number of the float type.
nextDouble() : reading a number of the double type.
For example, the following statements prompt the user to enter a double value from the console.
System.out. print ( "Enter a double value: " ); Scanner scanner = new Scanner(System.in); double d = scanner.nextDouble();
Note
More details on classes and objects will be introduced in Chapter 7, "Classes and Objects." For the time being, you will just have to accept that this is how to obtain input from the console. |
Note
The print method is identical to the println method except that println moves the cursor to the next line after displaying the string, but print does not advance the cursor to the next line when completed. |
Listing 2.9 gives an example that reads various types of data from the console using the Scanner class. A sample run of this program is shown in Figure 2.7.
1 import java.util.Scanner; // Scanner is in java.util 2 3 public class TestScanner { 4 public static void main(String args[]) { 5 // Create a Scanner 6 Scanner scanner = new Scanner(System.in); 7 8 // Prompt the user to enter an integer 9 System.out.print( "Enter an integer: " ); 10 int intValue = scanner.nextInt() ; 11 System.out.println( "You entered the integer " + intValue); 12 13 // Prompt the user to enter a double value 14 System.out.print( "Enter a double value: " ); 15 double doubleValue = scanner.nextDouble() ; 16 System.out.println( "You entered the double value " 17 + doubleValue); 18 19 // Prompt the user to enter a string 20 System.out.print( "Enter a string without space: " ); 21 String string = scanner.next (); 22 System.out.println( "You entered the string " + string); 23 } 24 } |
Tip
One benefit of using the console input is that you can store the input values in a text file and pass the file from the command line using the following command: java TestScanner < input.txt where input.txt is a text file that contains the data, as shown in Figure 2.8(a). The output of java TestScanner < input.txt is shown in Figure 2.8(b). You can also save the output into a file using the following command: java TestScanner < input.txt > out.txt |
Caution
By default, a Scanner object reads a string separated by whitespaces (i.e., ' ' , '\t' , '\f' , '\r' , and '\n' ). To read a string with embedded spaces, see §8.8.2, "Reading Data Using Scanner ." |
Pedagogical Note
You can use JOptionPane or Scanner for obtaining input, whichever is convenient . The examples in the book use JOptionPane for getting input for consistency. You can easily revise the examples using Scanner for getting input. |
Listing 2.6 uses input dialog boxes to obtain input. Alternatively, you can read input from the console in Listing 2.10. A sample run of the new program is shown in Figure 2.9.
1 import java.util.Scanner; 2 3 public class ComputeLoanAlternative { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a scanner for input 7 Scanner input = new Scanner(System.in); 8 9 // Enter yearly interest rate 10 System.out.print( "Enter yearly interest rate, for example 8.25: " ); 11 double annualInterestRate = input.nextDouble(); 12 13 // Obtain monthly interest rate 14 double monthlyInterestRate = annualInterestRate / 1200 ; 15 16 // Enter number of years 17 System.out.print( 18 "Enter number of years as an integer, \nfor example 5: " ); 19 int numberOfYears = input.nextInt(); 20 21 // Enter loan amount 22 System.out.print( "Enter loan amount, for example 120000.95: " ); 23 double loanAmount = input.nextDouble(); 24 25 // Calculate payment 26 double monthlyPayment = loanAmount * monthlyInterestRate / ( 1 27 “ 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12 )); 28 double totalPayment = monthlyPayment * numberOfYears * 12 ; 29 30 // Format to keep two digits after the decimal point 31 monthlyPayment = ( int )(monthlyPayment * 100 ) / 100.0 ; 32 totalPayment = ( int )(totalPayment * 100 ) / 100.0 ; 33 34 // Display results 35 System.out.println( "The monthly payment is " + monthlyPayment); 36 System.out.println( "The total payment is " + totalPayment); 37 } 38 } |