2017-04-18 74 views
1
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()或else if()语句中的原始System.out.print()?如何让我的while()循环返回if()语句?

P.S,我是新来的Java所以任何反馈将帮助:)谢谢!

+1

if语句必须位于while循环中。 –

+0

你能给我一个例子吗? – Crypto

+0

请注意,从'Scanner'中读取的称为'scanner'的''''''''''''很容易混淆。考虑交换这些名字。 –

回答

3

如果if语句只需要显示一次,就足以把while循环之后,因为如果类型启动或停止打破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

A 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. 
} 
+0

谢谢安迪,它工作!你能告诉我为什么你写了(真)吗?我似乎无法理解。 – Crypto

+0

'while(true)'仅仅意味着“继续直到我自己打破循环”。 –

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