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
Abdullah Nazeer
239 Pointswhat's wrong with my code?
import java.io.Console;
public class TreeStory {
public static void main(String[] args) {
Console console = System.console();
String ageAsString= console.readLine(" How old are you" );
int age=Integer.parseInt(ageAsString);
if(age<13)
{console.printf("Sorry you can't use this site\n");
System.exit(0);}
}
}
1 Answer
Fergus Clare
12,120 PointsHey Abdullah Nazeer! Great work on getting into JAVA! I think the problem is that you're trying to assign the string value of ageAsString directly from readLine instead using readLine to assign a value after the System.out.print prompts the user for a command. That's why you would be getting a nullPointerException. Consider the following code which worked well for me (compiled with no errors and is able to check for your conditions):
import java.io.Console; //import io
public class Test { //test class saved and named as Test.java for testing on JVM(you can ignore this part if using treehouse)
public static void main (String[] args) {
Console console = System.console(); //create a new console object
System.out.print("Enter your age: "); //prompt the user for their age
String ageAsString= console.readLine(); //store the input of the user in value "ageAsString
int age=Integer.parseInt(ageAsString); //read the string value using parseInt and assign value to new variable
if (age < 13) {//if the user is under age 13
console.printf("Sorry you can't use this site\n");//let them know they can't enjoy the site
System.exit(0);//close program
}//end if
}//end main method
}//end class
It's also good practice to either format your brackets like so in order to make code more readable:
//example of proper formatting for opening/closing braces 1
if (exampleCondition1 > exampleCondition2) {
yourCodeGoesHere;
}
//example of proper formatting for opening/closing braces 2
if (exampleCondition1 > exampleCondition2)
{
yourCodeGoesHere;
}
Keep up the good work! You're doing great!