如何在用户输入数据后重新运行java代码 [英] How to re run java code after user inputs data

查看:794
本文介绍了如何在用户输入数据后重新运行java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有一个基本的java'应用',显示人们是成人还是青少年等。我开始使用java,我无法找到如何在用户输入年龄后如此制作,以及他们被归类为节目的字符串我希望它重新运行整个事情,所以其他人可以去。我一直在寻找做一个循环,但这对我来说没有问题。这是代码:

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.

推荐答案

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

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
    }

或将所需代码放入方法

public static void ageCheck()
{
  //code that is currently in main method
}

它将通过主方法调用

this.ageCheck();

这篇关于如何在用户输入数据后重新运行java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆