问题
//some code here
String x;
while ((x = inputStream.readLine()) != null) {
System.out.println(inputStream.readLine());
}
inputStream.close();
}
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
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
回答1:
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();
回答2:
In your first example, you call readLine()
twice but only print every second value. That is, the value assigned to x
in your while
expression is not printed. When you use System.out.println(x);
, you print every value.
回答3:
This bit of code:
x = inputStream.readLine()
Reads the next line and stores it in x
. But then you never use x
. Instead, you do this:
System.out.println(inputStream.readLine());
That reads the next line after the one stored in x
and prints it out. Replace that with:
System.out.println(x);
That will print out the line you just read in the loop condition.
来源:https://stackoverflow.com/questions/54846573/why-my-java-while-loop-iterates-half-times