Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kurt Daisley
4,228 PointsCurious console.readLine Question
Had one question about the readLine method.
If we declare a string variable: String ageAsString = console.readLine("Type in your age: "); doesn't the whole line (Type in ... etc., including the answer from the user) become a string?
If so, how then do we apply the parseInt method to the string "Type in your age: 34" and have the result change only the "34" part of the string to an int?
Is that the readLine method only reads the input from the user, and ignores the rest of the string?
I tried doing this in jshell.
I typed String ageInput = "Type in your age: 45";
and got this result: ageInput ==> "Type in your age: 45"
Then I typed: int age = Integer.parseInt(ageInput);
and got the following voluminous error:
| java.lang.NumberFormatException thrown: For input string: "Type in your age: 45"
| at NumberFormatException.forInputString (NumberFormatException.java:65)
| at Integer.parseInt (Integer.java:652)
| at Integer.parseInt (Integer.java:770)
| at (#2:1)
Can anyone satisfy my curiosity and explain why this doesn't work?
1 Answer
andren
28,558 PointsIs that the readLine method only reads the input from the user, and ignores the rest of the string?
That is correct. console.readLine reads input until it hits a line break (hence the name) but input is only text actually input by the user, not text printed to the screen by your code.
So ageAsString will contain whatever the user typed themselves, nothing more.