gpt4 book ai didi

java - 如何在用户输入数据后重新运行java代码

转载 作者:行者123 更新时间:2023-12-02 04:53:12 24 4
gpt4 key购买 nike

嘿,我有一个基本的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();
}

任何帮助将不胜感激。我确信这非常简单,但我错过了一些东西。

最佳答案

你可以把它放在一个循环中,例如

 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
}

它将由 main 方法调用

this.ageCheck();

关于java - 如何在用户输入数据后重新运行java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com