繁体   English   中英

如何使我的while()循环返回到if()语句?

[英]How do I make my while() loop go back to an if() statement?

package somePackage;

import java.util.Scanner;

public class SomeClass {
    private static Scanner input;

    public static void main(String[] args) {

        input = new Scanner(System.in);
        System.out.print("Please enter a command (start or stop) : ");
        String scanner = input.nextLine();

        if ("start".equals(scanner)) {
            System.out.println("System is starting");
        } else if ("stop".equals(scanner)) {
            System.out.println("System is closing");
        }

        while (!"start".equals(scanner) && (!"stop".equals(scanner))) {
            System.out.print("Please try again : ");
            scanner = input.nextLine();
        }
    }
}

当用户不输入“开始”或“停止”时。 该程序将要求用户“重试:”。 假设用户输入“开始”之后,输出将为空白。 如何使循环返回到if()或if()语句中的原始System.out.print()?

PS,我是Java新手,所以任何反馈都可以帮助您:)谢谢!

如果if语句仅需要显示一次,就足以将其放在while循环之后,因为if类型start或stop break进入while循环,它将打印正确的消息,例如:

public class SomeClass {
    private static Scanner input;

    public static void main(String[] args) {

        input = new Scanner(System.in);
        System.out.print("Please enter a command (start or stop) : ");
        String scanner = input.nextLine();

        while (!"start".equals(scanner) && (!"stop".equals(scanner))) {
            System.out.print("Please try again : ");
            scanner = input.nextLine();
        }
        if ("start".equals(scanner)) {
            System.out.println("System is starting");
        } else if ("stop".equals(scanner)) {
            System.out.println("System is closing");
        }
    }
}

while循环无法“返回”其主体外部的语句。

您需要将要循环回到循环体内的所有内容。 例如:

System.out.print("Please enter a command (start or stop) : ");
while (true) {
  scanner = input.nextLine();

  if ("start".equals(scanner)) {
    System.out.println("System is starting");
    break;  // Exits the loop, so it doesn't run again.
  } else if ("stop".equals(scanner)) {
    System.out.println("System is closing");
    break;
  }

  // No need for conditional, we know it's neither "start" nor "stop".

  System.out.print("Please try again : ");
  // After this statement, the loop will run again from the start.
}

您可以简单地循环,直到获得所需的输出为止。 使用do-while的示例:

input = new Scanner(System.in);

String scanner;

do {
    System.out.print("Please enter a command (start or stop) : ");
    scanner = input.nextLine();
} while (!"start".equals(scanner) && !"stop".equals(scanner));

if ("start".equals(scanner)) {
    System.out.println("System is starting");
}
else if ("stop".equals(scanner)) {
    System.out.println("System is closing");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM