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

Java Java Basics Perfecting the Prototype Parsing Integers

Andrew D.
Andrew D.
2,937 Points

Why Can't We Just Read It In As Int?

I'm fairly fluent in C++.. and don't know anything about Java.. but is it really necessary to parse ints from strings, and not simply read in the age as an int and use that for the if condition?

Seems kinda odd... but perhaps that's how it's done in Java!

1 Answer

Michael Norman
PLUS
Michael Norman
Courses Plus Student 9,399 Points

Technically you can when using the Scanner object. Reading things in as string and parsing to integers gives another opportunity to teach new material though. I have not finished all of the Java track yet though so Craig may get to this soon. Here is an example if you are curious.

import java.util.Scanner;

public class Test{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);

    System.out.print("Enter your age: ");
    int age = in.nextInt();
    System.out.printf("Your age is %d", age + 2);
  }
}
Andrew D.
Andrew D.
2,937 Points

I see! Thank you.