Java While Loop and If statement

In summary, the code is trying to read a newline character, but it gets translated into two other characters in different operating systems.
  • #1
whitehorsey
192
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
  • #2
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.
 
  • #3
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".
 
  • #4
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. =/
 
  • #5
Code:
if(x== ' ')
{
	// ...
} else {
	// we have \n
}
If the while works as intended, this is a workaround.
 
  • #6
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.
 
  • #7
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."
 
  • #8
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
 
  • #9
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.
 

1. What is a Java While Loop?

A Java While Loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true. It checks the condition at the beginning of each iteration and continues to execute the code until the condition evaluates to false.

2. How do you write a While Loop in Java?

To write a While Loop in Java, you need to use the keyword "while" followed by a set of parentheses enclosing the condition. Inside the curly braces, you can include the code that you want to be executed repeatedly. Make sure to include a way to change the condition to eventually evaluate to false to avoid an infinite loop.

3. What is the purpose of using a While Loop?

The purpose of a While Loop is to execute a block of code repeatedly while a specific condition is true. This is useful for tasks that need to be repeated until a certain condition is met, such as user input validation or data manipulation.

4. How does a While Loop differ from a For Loop?

A While Loop differs from a For Loop in that a While Loop only requires a condition and does not have a set number of iterations. A For Loop, on the other hand, has a defined number of iterations and usually includes a counter variable. While Loops are generally used when the number of iterations is unknown, while For Loops are used when the number of iterations is known.

5. When should you use an If statement in a While Loop?

An If statement can be used in a While Loop to add additional logic and control the flow of the code. It allows you to execute a set of statements only if a certain condition is met within the While Loop. This can be useful for adding extra conditions or breaking out of the loop based on certain criteria.

Similar threads

  • Programming and Computer Science
Replies
2
Views
634
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
14
Views
3K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
9
Views
700
  • Programming and Computer Science
Replies
7
Views
2K
  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
Back
Top