【问题标题】:How to restart the main method?如何重启main方法?
【发布时间】:2017-11-30 15:24:03
【问题描述】:
public class Main {

    public static void main(String[] args) {

        System.out.println("Please enter a math value.");
        Scanner sayiyaz = new Scanner(System.in);

        if(sayiyaz.hasNextInt()) {
            int sayi1 = sayiyaz.nextInt();
        }
        else {
            System.out.println("I wish u could know what is a math value .");
        }
    }
}

在 else 代码块中,我想从头开始重新启动“main”方法并提出相同的问题。

但是怎么做呢?

【问题讨论】:

  • 阅读有关循环的教程:Java Control Flow Statements
  • 你可以通过重新运行程序来做到这一点:)
  • 致电main(args)
  • 我很确定“X”可以是一个数学值。
  • @E_net4 其他数学值包括确定性、泛化、普遍性、抽象性 - scholarworks.umt.edu/cgi/…

标签: java


【解决方案1】:

如果你愿意,你可以调用它(就像 Sudhakar 建议的那样),但我假设你只是想请求输入,直到你得到适合你需要的东西,在这种情况下你有一个更好的解决方案

  public static void main(String[] args) {
    boolean done = false;
    Integer sayi1 = null;
    do {
        System.out.println("Please enter a math value.");
        Scanner sayiyaz = new Scanner(System.in);
        if (sayiyaz.hasNextInt()) {
            sayi1 = sayiyaz.nextInt();
            done = true;
        } else {
            System.out.println("Input is wrong ");
        }
    } while (!done);

    System.out.println("Here is youre  input " + sayi1);
}

【讨论】:

    【解决方案2】:

    答案是你不想重启main。这是 Java 虚拟机用来启动应用程序的入口点。做你想做的最简单的方法是使用循环,比如:

    while (true) {
      System.out.println("Please enter a math value");
    
      // The rest of your code.
    
      if (finished)
        break;
    }
    

    【讨论】:

    • 啊哈就是大师!非常感谢:)我错过了你的观点:)
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2016-01-22
    • 2021-12-21
    • 1970-01-01
    • 2017-02-13
    • 2021-10-12
    相关资源
    最近更新 更多