java - java while 循环不能正常工作

标签 java loops io

在以下代码中,要继续程序,用户应按 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/

相关文章:

Java:如何使用socket发送和接收数据?

java - Spring3 的 @Value 注释在我的程序中不起作用

javascript - Angular JS - ng-repeat 和循环条件

c++ - 混合 fstream 和 stdio 有技术上的危险吗?

java - 尝试重命名计算机或在 Java 中执行 .bat 文件

java - 如何在 MainActivity 运行时显示 SplashScreen

java - 我如何从第 10 行读取(例如)代码的第 5 行?

javascript - 循环不会遍历所有元素

.net 文本分隔库?

python - 如何将 scipy 稀疏矩阵保存到 Parquet 文件中