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

时间:2017-04-18 21:47:52

标签: java eclipse

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();
        }
    }
}

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

P.S,我是Java的新手,所以任何反馈都会有所帮助:)谢谢!

3 个答案:

答案 0 :(得分:3)

如果if语句只需要显示一次,就足以将其放在while循环之后,因为如果键入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");
        }
    }
}

答案 1 :(得分:1)

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.
}

答案 2 :(得分:1)

你可以简单地循环,直到你得到所需的输出;使用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");
}