2017-04-18 32 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"); 
}