Lesson+07+-+Input+from+the+Keyboard

=Inputting an Integer= Scanner user_input = new Scanner(System.in); /* Create a Scanner Object */ System.out.println("Enter an integer "); /* Prompt the user to type an integer */ int user_int = user_input.nextInt; /* get the next int after the prompt*/ = = =Inputting a Double= Scanner user_input = new Scanner(System.in); /* Create a Scanner Object */ System.out.println("Enter a double "); /* Prompt the user to type a decimal*/ double user_double = user_input.nextDouble; /* get the next doublefter the prompt*/ = = =Inputting a String= Scanner user_input = new Scanner(System.in); /* Create a Scanner Object */ System.out.println("Enter a string "); /* Prompt the user to type string */ String user_string = user_input.next; /* get the next String after the prompt*/

=Multiple Inputs= Scanner user_input = new Scanner(System.in); /* Create a Scanner Object */ System.out.println("Enter 2 integers separated by a space "); /* Prompt the user to type 2 integers */ int user_int1 = user_input.nextInt; /* get the first int after the prompt*/ int user_int2 = user_input.nextInt; /* get the second int */

=Input an Entire Line of Text= Scanner user_input = new Scanner(System.in); /* Create a Scanner Object */ System.out.println("Enter a string "); /* Prompt the user to type string */ String lineOfText = user_input.nextLine;

=Imports necessary= import java.io.*; /* Bring in all the classes in java.io package (a package is group of related classes) */ import java.util.*; /* Bring in all the classes in the java.util package */

The * is the wildcard. It is saying that bring in all the classes in java.io and java.util.

Better programming is to bring in just the classes you need. To bring in just the Scanner class; import java.util.Scanner;

=Mysterious Object= Scanner user_input = new Scanner(System.in); This creates a Scanner object. Remember java is an object-oriented programming language. We are going to create many objects like bugs, rocks, and other game pieces. When you create an object, you get access to the objects methods nextInt, nextDouble, next, nextLine.

=Anomaly (Strange happenings)= You can do multiple nexInt and/or nextDouble and/or next in any order with one scanner object. However, java won't like if you follow a nextInt or nextDouble with a nextLine. If you need to do that, you need to create a second scanner object like: Scanner user_input2 = new Scanner(System.in);