Lesson+07


 * Lesson #07: Input from the Keyboard - Grant

Inputting an integer:** Use the nextInt method to input an integer from the keyboard: code

import java.util.*; public class Tester { public static void main( String args[] ) { Scanner kbReader = new Scanner(System.in); //see “Mysterious //objects” on next page System.out.print(“Enter your integer here. ”); //enter 3001 int i = kbReader.nextInt; System.out.println(3 * i); //prints 9003 } }** code Inputting a double: Use the nextDouble method to input a double from the keyboard: code import java.util.*; public class Tester { public static void main( String args[] ) { Scanner kbReader = new Scanner(System.in); System.out.print(“Enter your decimal number here. ”); //1000.5 double d = kbReader.nextDouble; System.out.println( 3 * d ); //prints 3001.5 } }** code Inputting a String: Use the next method to input a String from the keyboard: code import java.util.*; public class Tester{ public static void main( String args[] ) { Scanner kbReader = new Scanner(System.in); System.out.print(“Enter your String here. ”); //Enter One Two String s = kbReader.next; //inputs up to first white space System.out.println( “This is the first part of the String,… ” + s); s = kbReader.next; System.out.println( “This is the next part of the String,… ” + s); } }** code Output would be as shown below: Enter your String here. One Two This is first part of the String,... One This is next part of the String,... Two
 * import java.io.*; //see “Imports necessary” on next page
 * import java.io.*;
 * import java.io.*;

In a similar way nextInt and nextDouble can be used multiple times to parse data input from the keyboard. For example, if 34 88 192 18 is input from the keyboard, then nextInt can be applied four times to access these four integers separated by white space.
 * Multiple inputs:**

Using a single Scanner object, the methods nextInt, nextDouble, next, and nextLine may be used in any sequence with the following exception: It is not permissible to follow nextInt or nextDouble with nextLine. If it is necessary to do this, then a new Scanner object must be constructed for use with nextLine and any subsequent inputs.
 * An anomaly:**