Reputation: 309
Hey I have a basic java 'app' showing if people are an adult or teen etc.. I am starting out with java and I can't find how to make it so after a user has input an age, and the string of what they are classified as shows I would like it to re run the whole thing again so someone else can have a go. I have been looking into doing a loop but that hasn't worke dout for me.. Here is the code:
public static void main(String[] args)
{
//Declare local variables
int age;
Scanner in = new Scanner(System.in);
//Prompt user for Age
System.out.print("Enter Age: ");
age = in.nextInt();
if(age > 17)
{
System.out.println("This persons age indicates that they an adult");
}
else if (age > 12)
{
System.out.println("This persons age indicates that they are a teenager");
}
else if (age >= 0)
{
System.out.println("This persons age indicates that they are a child");
}
else
{
System.out.println("That age is invalid");
}
//Close input
in.close();
}
Any help would be greatly appreciated. I am sure it is super simple and I have missed something.
Upvotes: 0
Views: 2448
Reputation: 4534
You can call your main()
recursively
After this in.close();
statement just call your main()
like this
in.close();
main(null);
But you must put some conditions when to stop the execution of you program.
Upvotes: 0
Reputation: 73
You can put it in a loop such as
public static void main(String[] args)
{
//Declare local variables
int age;
Scanner in = new Scanner(System.in);
while(true){
//Prompt user for Age
System.out.print("Enter Age: ");
age = in.nextInt();
if(age > 17)
{
System.out.println("This persons age indicates that they an adult");
}
else if (age > 12)
{
System.out.println("This persons age indicates that they are a teenager");
}
else if (age >= 0)
{
System.out.println("This persons age indicates that they are a child");
}
else
{
System.out.println("That age is invalid");
}
}
//Close input
in.close(); //Note that this happens outside the loop
}
or put the needed code in a method
public static void ageCheck()
{
//code that is currently in main method
}
it would be called from the main method by
this.ageCheck();
Upvotes: 2