import java.io.IOException;public class WhileTest1 {
public static void main(String[] args) throws IOException {
System.out.print("Are you feeling better about programming?(Y or N):");
System.out.flush();
char response = (char) System.in.read();
while (response != 'y' && response != 'n') {
System.out.println("Invalid letter.");
System.out.println("Enter only 'y' or 'n':");
response = (char) System.in.read();
}
if (response == 'y') {
System.out.println("I'm glad.");
} else {
System.out.println("Keep trying.");
}
}
}为什么这个在while里没有flush还是能继续程序运行也不出错,再次输入一段字符串仍会进入while进行判断。
另外如果是输入字符串,怎么使非正确正确输入的情况下while仅循环一次就进入下一次的输入操作(当前情况下仅输入一个字符仍会循环3次,即输入的字符、换行、换车)。希望高手帮忙解答。

解决方案 »

  1.   

    用Scanner这个类吧
    System.out.print("Are you feeling better about programming?(Y or N):");
    System.out.flush();
    Scanner s=new Scanner(System.in);
    String response =s.next();
    while (!response .equals("y") && !response.equals("n")) {
    System.out.println("Invalid letter.");
    System.out.println("Enter only 'y' or 'n':");
    response=s.next();
    }  if (response.equals("y")) {
    System.out.println("I'm glad.");
    } else {
    System.out.println("Keep trying.");
    }
      

  2.   


    public class WhileTest1 {
    public static void main(String[] args) throws IOException {
    System.out.print("Are you feeling better about programming?(Y or N):");
    System.out.flush();//这里写不写无所谓,但是往流中写入数据的时候最好写上(要不可能会有一些数据写不进去)
    char response = (char) System.in.read();
    while (response != 'y' && response != 'n') {
    System.out.println("Invalid letter.");
    System.out.println("Enter only 'y' or 'n':");
    response = (char) System.in.read();
    }
    if (response == 'y') {//写成'y' == response
    System.out.println("I'm glad.");
    } else {
    System.out.println("Keep trying.");
    }
    }
    }      你的其他问题我不明白你到底要表达什么意思?
      

  3.   

    谢谢两位的解答经过单步跟踪,发现while语句自行过程中总有循环\r和\n这2个,知道为什么总是会多循环2次了。