User Input Flashcards
What does the built in Scanner class do?
It allows us to create a Scanner object which can be used to get and store input(s).
How is the Scanner class imported?
At the top of our code we import the class with this line of code:
import java.util.Scanner;
What is the line of code that creates a new object of the Scanner named input from type System.in
Scanner input = new Scanner(System.in);
What does using the argument System.in allow in the following code?
Scanner input = new Scanner(System.in);
By using System.in as an argument to create a Scanner type object, input can be read from the standard input channel, which for us is the terminal.
What type of value does the nextLine() Scanner input method expect?
String. This method reads input until the end of a line.
What type of value does the next() Scanner input method expect?
String. This method reads input until it reaches a space.
What would be the Scanner method for the following data types?
byte
long
double
nextByte()
nextLong()
nextDouble()
The Scanner class contains several methods, with directly related names, to read primitive data type input.
What happens if an unexpected input type is entered into a scanner method?
A InputMismatchException will be thrown.
Why is it recommended that we close the Scanner when it is no longer being used?
It allows java to reclaim the memory used by the object.
What is the syntax used to close the scanner object named keyboard?
keyboard.close();
What is the syntax to read a line of text input from the Scanner object keyboard and save it into the String variable userId?
String Userid = keyboard.nextLine()
Scanner is the easiest and commonly used class built into java that can be used to read input. What are a couple others?
BufferedReader
InputStreamReader
How can we check to see if the input data type we get is the correct type?
By using input type checking methods in if statements. These return a boolean value indicating if the input matches the expected value type.
scanner.hasNextInt()
scanner.hasNextDouble()
What would the syntax be to check if the input from the user the Scanner object keyboard receives is of the int data type?
keyboard.hasNextInt()
This returns a Boolean and can be used in loops or if statements to ask for input again.