Parsing Numbers from Input
Convert text to numbers.
Lines Are Always Strings
readLine() always gives you a String, even when the user types 42. To do math, you must parse that text into a number.
Java provides helper methods like Integer.parseInt and Double.parseDouble for exactly this.
Integer.parseInt
Integer.parseInt(String) converts text like "42" into the int value 42.
Once parsed, you can add, multiply, or compare it like any number.
String text = "42";
int n = Integer.parseInt(text);
System.out.println(n + 1);All lessons in this course
- Why BufferedReader
- Reading Lines
- Parsing Numbers from Input
- Closing Streams Safely