嘿,我有一个基本的java'应用程序'显示人们是成人还是青少年等。我开始使用java,但是在用户输入年龄之后我找不到如何做到这一点,并且他们被归类为节目的字符串我希望它重新运行整个事情,所以其他人可以去。我一直在研究做一个循环,但这对我来说没有问题。这是代码:
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();
}
非常感谢任何帮助。我确信它非常简单,我错过了一些东西。
答案 0 :(得分:2)
您可以将其置于循环中,例如
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
}
或将所需代码放入方法
public static void ageCheck()
{
//code that is currently in main method
}
将通过
从主方法调用this.ageCheck();
答案 1 :(得分:0)
你可以做一段时间(真实)循环来永远运行
答案 2 :(得分:0)
您可以递归拨打main()
在此in.close();
声明之后,只需按此main()
致电
in.close();
main(null);
但是你必须在何时停止执行你的程序。