2017-06-02 320 views
0

我对此非常陌生,并且正在通过一个教程进行工作,但想用一段时间循环来体验它,以便程序重复,直到“K”为止由用户输入。 不幸的是,当输入不正确的字符时,这似乎读取回车符和换行符。这意味着“错误”被输出三次而不是一次。 有什么办法可以排除这些只读字符吗?在此先感谢Java:如何从System.in.read中排除回车/换行

class Guess{ 

    public static void main(String args[]) 
    throws java.io.IOException { 
     char ch, answer ='K'; 


     System.out.println("I'm thinking of a letter between A and Z."); 
     System.out.print("Can you guess it:"); 
     ch = (char) System.in.read(); //read a char from the keyboard 

     while (ch != answer) { 
     System.out.println("**WRONG**"); 
     System.out.println ("I'm thinking of a letter between A and Z."); 
     System.out.print("Can you guess it:"); 
     ch = (char) System.in.read(); //read a char from the keyboard 
     if (ch == answer) System.out.println("**Right**"); 

     } 

    } 
} 
+0

你可以尝试使用do-while语句。 – Bubletan

回答

0

这只是statments顺序。 试试这个

public class Guess { 

    public static void main(String args[]) 
      throws java.io.IOException { 
     char ch, answer = 'K'; 

     System.out.println("I'm thinking of a letter between A and Z."); 
     System.out.print("Can you guess it:"); 
     ch = (char) System.in.read(); //read a char from the keyboard 

     while (ch != answer) { 


      ch = (char) System.in.read(); //read a char from the keyboard 
      if (ch == answer) { 
       System.out.println("**Right**"); 
       break; 
      }else{ 
       System.out.println("**WRONG**"); 
      } 
      System.out.println("I'm thinking of a letter between A and Z."); 
      System.out.print("Can you guess it:"); 

     } 

    } 

} 
+0

感谢您的反馈,您刚刚提出了修改建议,并且可以正常工作! – TMC

+0

@TMC选择一个答案作为其他人找到答案的正确答案之一。 – Krismorte

+1

不知道我能做到这一点,现在就完成了,谢谢你让我知道! – TMC

1

我会建议使用Scanner和读取线时,用户点击返回作为read认为返回为其他字符,例如:

char answer ='K'; 
Scanner scanner = new Scanner(System.in); 
System.out.println("I'm thinking of a letter between A and Z."); 
System.out.print("Can you guess it:"); 
String ch = scanner.nextLine(); //read a char from the keyboard 

while (ch.length() > 0 && ch.charAt(0) != answer) { 
    System.out.println("**WRONG**"); 
    System.out.println ("I'm thinking of a letter between A and Z."); 
    System.out.print("Can you guess it:"); 
    ch = scanner.nextLine();//read a char from the keyboard 
} 
System.out.println("**Right**"); 
scanner.close(); 
+0

嗨,感谢您的反馈,我将不得不考虑扫描仪功能,但是我发现我得到了多行相同的结果,但由于另一个答案指出我的订购已关闭,因此结合使用有效 ! – TMC