2016-04-14 70 views
0

這個問題內捕獲鍵盤輸入是從下面的鏈接的擴展:試圖while循環

Why is my c != 'o' || c != 'x' condition always true?

enter image description here

相應的代碼也是在鏈路;我編輯了導致問題的布爾部分,因此它取得了正確的值。

現在,問題(如上圖所示)是在java程序捕獲輸入後,循環會執行三個循環,直到等待下一個輸入爲止。

爲什麼這樣做?我該如何解決它?

+0

它不應該打印此3次。你能再次在這裏粘貼你的確切代碼嗎? – Foolish

回答

1
import java.util.Scanner; 

公共類test1的{

public static void main (String args[]) { 

    Scanner sc = new Scanner (System.in); 
    boolean game_start=false; 
    char c; 

while(!game_start){ 
     System.out.println("press o to play first"); 
     System.out.println("press x to play second"); 

     c = sc.next().charAt(0); 

     System.out.println("You entered " + c); 

     if(c!='o' && c!='x') 
      System.out.println("you can only enter o or x!"); 
     else 
      game_start = true; 
     } 
} 

}

+0

我測試過了,效果很好。 –

+0

我試圖不使用掃描儀,因爲我認爲這只是字符串,但我想這種方式更容易。謝謝你的回答! –