Java While Loop and If statement

Click For Summary

Discussion Overview

The discussion revolves around a Java programming issue related to reading input from a file that contains blank lines. Participants are exploring the behavior of a while loop and if statements when handling newline characters, particularly in different operating systems.

Discussion Character

  • Technical explanation
  • Debugging
  • Debate/contested

Main Points Raised

  • One participant notes that the character x is equal to a newline but does not enter the corresponding if statement, suggesting a potential issue with how newline characters are handled.
  • Another participant mentions that newline characters are represented differently across operating systems, proposing that changing the condition to check for ASCII 13 might resolve the issue.
  • Some participants argue that Java should treat end-of-lines consistently, similar to C and C++, and suggest that the problem may lie in unseen parts of the code.
  • A suggestion is made to replace the second if condition with an else statement if x can only take two values within the loop.
  • One participant expresses frustration with the lack of clarity in the problem due to insufficient code context, emphasizing the need for a complete runnable example for effective debugging.
  • Another participant points out that Java supports Unicode character constants, which could be a solution for representing certain characters.

Areas of Agreement / Disagreement

Participants express differing views on the handling of newline characters in Java and the potential causes of the issue. There is no consensus on the exact problem or solution, as multiple hypotheses are presented.

Contextual Notes

Participants highlight the importance of providing complete code for debugging, as the current snippets may not fully represent the issue. There are also mentions of operating system-specific behavior that could affect character reading.

whitehorsey
Messages
188
Reaction score
0
I am reading an input file that has blank lines. x reads character by character. x is equal to a new line so it goes into the while loop but skips the if x == '\n'. It's suppose to go inside the if statement but it doesn't. I tried debugging the code and printed out to double check x is holding a new line. What am I doing wrong?

Code:
while(x == ' ' || x== '\n')
{
	if(x== ' ')
	{
		//...
	}
		
	if(x== '\n')
	{
		//...
	}
}
 
Last edited by a moderator:
Technology news on Phys.org
whitehorsey said:
I am reading an input file that has blank lines. x reads character by character. x is equal to a new line so it goes into the while loop but skips the if x == '\n'. It's suppose to go inside the if statement but it doesn't. I tried debugging the code and printed out to double check x is holding a new line. What am I doing wrong?

Code:
while(x == ' ' || x== '\n')
{
	if(x== ' ')
	{
		//...
	}
		
	if(x== '\n')
	{
		//...
	}
}
The newline character gets translated by the OS into two characters in Windows (ASCII 13 and ASCII 10) and one character in Linux, Unix, and related OSes (ASCII 13, I believe). If you change your second if condition to x == '\0xD', which is 13 in hex, I think you'll find the character you're looking for.

BTW, you're adding too many TAB characters in your code. The braces should be indented at the same level as the while, if, for, etc they're associated with. If you indent the braces and indent the statements inside the braces, parts of your code soon extend way to the right, making it necessary for someone reading it to have to scroll to see all of the line.

Indenting code where appropriate is good to do, but there can be too much of a good thing.
 
Jave should treat end-of-lines the same way as C and C++. The operating system specific details are suppressed, and your code always see a single '\n' character, unless you open the file as raw binary data (which you shouldn't, if it contains text split into "lines").

I suspect the problem is in some code the OP hasn't shown us. There must be some way(s) to exit from the while loop, otherwise any blank or newline character would loop for ever. Or, depending how the file is read, x might never be set to a newline character.

As a detail, if x can only have two values inside the while loop (i..e its value doesn't change in the code we can't see), if would be neater to replace "if (x == '\n')" with "else".
 
Mark44 said:
The newline character gets translated by the OS into two characters in Windows (ASCII 13 and ASCII 10) and one character in Linux, Unix, and related OSes (ASCII 13, I believe). If you change your second if condition to x == '\0xD', which is 13 in hex, I think you'll find the character you're looking for.

BTW, you're adding too many TAB characters in your code. The braces should be indented at the same level as the while, if, for, etc they're associated with. If you indent the braces and indent the statements inside the braces, parts of your code soon extend way to the right, making it necessary for someone reading it to have to scroll to see all of the line.

Indenting code where appropriate is good to do, but there can be too much of a good thing.

Oh the tabs were due to copy and paste but in my code it is indented correctly. I printed out print statements and it does read x as 13. It won't let me change the if to '\0xD' because it is not a character constant.

AlephZero said:
Jave should treat end-of-lines the same way as C and C++. The operating system specific details are suppressed, and your code always see a single '\n' character, unless you open the file as raw binary data (which you shouldn't, if it contains text split into "lines").

I suspect the problem is in some code the OP hasn't shown us. There must be some way(s) to exit from the while loop, otherwise any blank or newline character would loop for ever. Or, depending how the file is read, x might never be set to a newline character.

As a detail, if x can only have two values inside the while loop (i..e its value doesn't change in the code we can't see), if would be neater to replace "if (x == '\n')" with "else".

I created a blank text file in eclipse and pressed enter three times (three new lines). The above is the whole while loop everything that is inside the if/else statement is to assign x with a new value (the next character). I switched it to else but it's still the same. =/
 
Code:
if(x== ' ')
{
	// ...
} else {
	// we have \n
}
If the while works as intended, this is a workaround.
 
mfb said:
Code:
if(x== ' ')
{
	// ...
} else {
	// we have \n
}
If the while works as intended, this is a workaround.

I debugged it again and it doesn't go into the while loop anymore.

In the first line x = 13.
Second line x = 10.
Third line x = 10.
 
There are probably least 57 different ways to read characters from a file in Java. If you don't show us EXACTLY what ALL the relevant code says, this is just a guessing game IMO.

A good principle for debugging code is, "if there is nothing wrong with the code you are looking at, you should be looking somewhere else."
 
It's not clear where the problem lies from that small amount of code.
You should post a complete runnable example.
e.g.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Read {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("text.txt"));
        int emptyLines = 0;
        String line = in.readLine();
        while(line != null && line.matches("\\s*")) {
            emptyLines++;
            line = in.readLine();
        }
        System.out.println("There are " + emptyLines + " empty lines at the start of the file.");
        int n = emptyLines + 1;
        while(line != null) {
            System.out.println(n + ". line = " + line);
            line = in.readLine();
            n++;
        }
        in.close();
    }
}

if text.txt looks like this
Code:
abc
def
ghi

The output will be
Code:
There are 4 empty lines at the start of the file.
5. line = abc
6. line = def
7. line = ghi
 
whitehorsey said:
Oh the tabs were due to copy and paste but in my code it is indented correctly. I printed out print statements and it does read x as 13. It won't let me change the if to '\0xD' because it is not a character constant.
This would be a character constant in C, C++, C# (I think), and a few other languages. Java can use Unicode character constants, such as '\u000D'. I believe that would work.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K