本文介绍了为什么我的Java while循环迭代一半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//some code here
    String x;
    while ((x = inputStream.readLine()) != null) {
        System.out.println(inputStream.readLine());
    }
    inputStream.close();
}

你好,我是Java的初学者,我的while循环应提供类似
的输出aaasd1
aaasd2
aaasd3
aaasd4
aaasd5
aaasd6
但这给了
aaasd2
aaasd4
aaasd6

Hello I am beginner at Java and My while loop should give an output like
aaasd1
aaasd2
aaasd3
aaasd4
aaasd5
aaasd6
But it gives
aaasd2
aaasd4
aaasd6

当我将println更改为 System.out.println(x); 时,它会提供应有的输出.有谁知道这是什么问题.感谢您的帮助

When i change the println to System.out.println(x); it gives output like it should do. Do anyone know what is the problem. Thanks for help

推荐答案

每次调用 inputStream.readLine()时,您都会读取一行并将文件指针前进到下一行,因为您这样做它两次,一次在 while循环标头中,一次在打印时,则仅打印第二行.改为打印x

Every time you call inputStream.readLine() you read one line and advance the file pointer to the next line and since you do it twice, once in the while loop header and once when printing then only every second line is printed. Print x instead

String x;
while ((x = inputStream.readLine()) != null) {
    System.out.println(x);
}
inputStream.close();

这篇关于为什么我的Java while循环迭代一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:35