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次,即输入的字符、换行、换车)。希望高手帮忙解答。
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次,即输入的字符、换行、换车)。希望高手帮忙解答。
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.");
}
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.");
}
}
} 你的其他问题我不明白你到底要表达什么意思?