Java User Input: Reading Data from Keyboard with System.in and Scanner - Quiz

Total: 6 questions

1. 

How do you read an integer from the keyboard in Java?

Create a Scanner based on System.in and call nextInt(): int n = new Scanner(System.in).nextInt();

2. 

Which package is the Scanner class imported from?

From the java.util package. You need to add import java.util.Scanner; before using it.

3. 

Why check hasNextInt() before nextInt()?

The hasNextInt() method checks whether an integer can be read and returns true or false. Without this check, if the user enters something that is not a number, nextInt() crashes the program with an InputMismatchException.

4. 

Why does nextLine() read an empty string after nextInt()?

Because nextInt() reads only the number, leaving the newline character from the Enter key in the buffer. The next nextLine() reads that leftover and returns an empty string. The fix is to add a throwaway nextLine() after nextInt().

5. 

What is the difference between next() and nextLine()?

The next() method reads a single word, up to the first space. The nextLine() method reads the entire line, including spaces, until Enter is pressed.

6. 

Why might nextDouble() fail to read a number with a period?

The nextDouble() method uses the decimal separator defined by the system locale. In some locales the separator is a comma, so entering 3.14 may cause an error. You can set the locale explicitly with Locale.US to always expect a period.

Page 1 of 1