在以下代码中,要继续程序,用户应按 y 字符 但是当我按 y 时循环终止
public class JavaFile
{
int i = 0;
public void systemIO()throws java.io.IOException {
System.out.println("Enter the character");
i = System.in.read();
System.out.println("the character Enter by the user : "+(char)i);
System.out.println("the assci vlue "+i);
}
public void cntApp()throws java.io.IOException{
char cnt = 'y';
while(cnt =='y'){
systemIO();
System.out.println("press 'y' if you want continue");
cnt = (char)System.in.read();
System.out.println("The Entery value "+cnt);
}
}
public static void main(String args[]) {
try{
new JavaFile().cntApp();
}catch(java.io.IOException ioExe){
System.out.println(ioExe);
}
}
最佳答案
引用this answer .
您可以在 systemIO()
和 cntApp()
方法的末尾添加以下行,即在 System.in.read()
之后> 方法调用。
System.in.skip(System.in.available());
所以你的方法将如下所示。
public void systemIO() throws java.io.IOException {
System.out.println("Enter the character");
i = System.in.read();
System.out.println("the character Enter by the user : " + (char) i);
System.out.println("the assci vlue " + i);
System.in.skip(System.in.available());
}
public void cntApp() throws java.io.IOException {
char cnt = 'y';
while (cnt == 'y') {
systemIO();
System.out.println("press 'y' if you want continue");
cnt = (char) System.in.read();
System.out.println("The Entery value " + cnt);
System.in.skip(System.in.available());
}
}
注意:但是使用 Scanner(System.in)
是比直接使用 System.in.read() 更好的方法。
关于java - java while 循环不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850480/