Reading and validating console input
Program input arrives as text, and you decide how to interpret it.
How it works
Reading a whole line gives you the exact string to validate. Trim the leading and trailing spaces, check for blank input if your prompt allows it, and parse the rest. After parsing, still check application limits. For example, an integer can be valid Java input and still be an invalid seat count.
Walk through an example
A Scanner can read a line using nextLine(). Trim extra spaces, then call Integer.parseInt when you expect a whole number.
What to watch for
Handle malformed text and out-of-range values separately. Reading only complete lines avoids confusion when mixing methods that consume tokens and lines.
Code example
public class Main {
public static void main(String[] args) {
String line = " 42 ";
System.out.println(Integer.parseInt(line.trim()));
}
}Check your understanding
What number does parseInt produce after trim?
See the example and explanation
- Worked example
- Given
Input line: ' 42 ' - Answer
42
Trimming strips the surrounding spaces. Parsing then converts the two remaining digits to an integer.