Question
specs for UsingScanner UsingScanner Write a class called UsingScanner. This class has a main method. Remember to import class Scanner from library java.util. If you
specs for UsingScanner
UsingScanner
Write a class called UsingScanner. This class has a main method. Remember to import class Scanner from library java.util. If you don't have this line you will not be able to use the class Scanner.
what this program does:
1. ask user to enter an integer (see example below) 2. read the integer using a Scanner object 3. print "I read an integer: " followed with whatever integer was read (see examples below) 4. ask user to enter a double 5. read the double 6. print "I read a double: " followed with whatever double was read 7. ask user to enter a String 8. read the String 9. print "I read a String: " followed with whatever String was read
how to write it
0. import the Scanner class from the java.util package import java.util.Scanner; 1. create only one Scanner object connected to System.in Scanner input = new Scanner(System.in); 2. print "please enter a integer: " System.out.print("please enter a integer: "); 3. declare a variable of type int int x; 4. read an int from the user and assign it to the variable x = keyboard.nextInt(); 5. print "I read an integer: " + x System.out.println("I read an integer: " + x); 6. do the same for double and for String (use the same Scanner object for these)
Consuming the extra newline
There is a problem when you use the Scanner to read a new line just after reading a primitive type such as a double or an int. The following text is quoted from Gaddis 6e book: Keystrokes are stored in an area of memory that is sometimes called the keyboard buffer. Pressing the Enter key causes a newline character to be stored in the keyboard buffer. The Scanner methods that are designed to read primitive values, such as nextInt and nextDouble, will ignore the newline and return only the numeric value. The Scanner class's nextLine method will read the newline that is left over in the keyboard buffer, return it, and terminate without reading the intended input. Remove the newline from the keyboard buffer by calling the Scanner class's nextLine method, ignoring the return value.
Examples
(what the user typed is shown in boldface) % java UsingScanner please enter a integer: 0 I read an integer: 0 please enter a double: 23.5 I read a double: 23.5 please enter a String: hello world I read a String: hello world % java UsingScanner please enter a integer: -2018 I read an integer: -2018 please enter a double: 12345.98765 I read a double: 12345.98765 please enter a String: good bye I read a String: good bye %
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started