user3529942
user3529942

Reputation: 23

Java can't read that the character is a new line

if (first == true) {
    x = input.read(); // input is a Reader
    nextCharacter = input.read();
    first = false;
}
else {
    x = nextCharacter;
    nextCharacter = input.read();
    charPosition++;
}

while (x == ' ' || x == '\n') {
    if (x == ' ') {
        x = nextCharacter;
    }
    else {
        x = nextCharacter;
    }
}

I am reading an input text file that has three blank lines. x reads character by character. x is equal to a new line so it suppose to go into the while loop but it does not. I debugged the code and printed out to check if x is holding a new line. It prints out x= 13, x = 10, x = 10. In all three of these cases, it skips the while loop.

Another method I tried:

while(x == '\n') {
    System.out.println("entered");
    x = nextCharacter;
}

When I write it in its own while loop it will enter the loop the second time (x = 10) but come back out the third time when x = 10. Which isn't suppose to happen it should stay in the loop until it hits the end of file (x = -1).

I also tried Character.toString((char) nextChar) == "\r\n" but that has the same result as the first one.

What am I doing wrong?

Upvotes: 0

Views: 1892

Answers (3)

Braj
Braj

Reputation: 46841

I am reading an input text file that has three blank lines.

The better way is read line by line and check each line whether it is empty or not.

Sample code:

    BufferedReader reader = new BufferedReader(new FileReader(new File("resources/abc.txt")));

    String line = null;
    while ((line = reader.readLine()) != null) {
        if (!line.isEmpty()) {
            System.out.println(line);
            // do whatever you want to do with char array if needed
            // char[] arr=line.toCharArray();
        }
    }
    reader.close();

Upvotes: 1

Actimia
Actimia

Reputation: 135

You could attempt to use something like

while (Character.isWhitespace(x){
    // skip
}

The documentation for Character.isWhitespace(char)is here.

Upvotes: 0

Yavor
Yavor

Reputation: 321

"Blank line" may be a bit vague thing. Your "\r\n" attempt is close to the root cause of your issue (just strings should be compared via .equals instead of ==).

Another solution could be to create a proper input file where a new line is indeed just "\n" instead of "\r\n" (ascii codes 13, 10).

Upvotes: 0

Related Questions