Lecture 11 Getting Input from the users in JAVA
Lecture 11 Getting Input from the users in JAVA
This is because sc.nextInt() only reads the integer value and does not consume the newline
character.
The call to sc.nextLine() will read the leftover newline character instead of the intended input
string.
Explanation to Previous Question
• Scanner class in Java treats whitespace characters (including the
newline character) as delimiters by default.
• The next() method reads the next input token until it encounters a
delimiter (whitespace character) and returns the token as a string,
excluding the delimiter.
• In the case of nextLine(), it reads the entire line of input, including
the newline character at the end, and returns it as a string.
• Therefore, when you use sc.nextLine() to read input, it reads the
input line and also consumes the newline character left in the input
buffer.
Output?
import java.util.Scanner;
sc.nextLine();
Why do we need to import the Scanner class in our Java program, but
not the Math class when we use it?