2016-04-14 72 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

我试图不使用扫描仪,因为我认为这只是字符串,但我想这种方式更容易。谢谢你的回答! –