0
String[] lines = ascii.getText().split("\\n");
for(int i = 0; i < lines.length; i++){
    System.out.println(lines[i]);
    if(lines[i] == "")
        System.out.println("abc");
}

ascii is a JTextArea. This is a sample code I'm just testing it before I put it in my program. Right now it splits the lines from ascii into separate strings, and then displays them.

It does that correctly and includes the empty lines which I want. Now I want to check if line is empty (it can contain only spaces). I've tried with combinations of

if(lines[i] == "", " ", "\n"...)

but none of those worked. Can anyone explain how to do it?

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
user3562657
  • 167
  • 3
  • 15
  • 2
    Can you describe your problem in more detail (I am not sure what you mean by "*but what is actually in the empty string?*")? Anyway [don't compare strings with `==`](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Pshemo Nov 14 '14 at 03:28
  • `String#trim#isEmpty` is a pretty good start – MadProgrammer Nov 14 '14 at 03:32
  • Yeah, if there's an empty line, I want to mark that in the output file. So I need to know that empty line is saved at in the lines array – user3562657 Nov 14 '14 at 03:33
  • I tried lines[i].compareTo("", " ", and "\n") and they all returned can't convert from int to boolean – user3562657 Nov 14 '14 at 03:34
  • Because `compareTo` returns an integer for sorting purposes – Brandon Nov 14 '14 at 03:35
  • The crux of the problem above is that you are doing a reference equality check for `""`, not comparing the string values. You need to use `.equals`. However, the suggested `.isEmpty()` approach seems easier to read. – Brandon Nov 14 '14 at 03:35

1 Answers1

2

but what is actually in the empty string? I've tried if(lines[i] == "", " ", "\n"... and none of those worked. Can anyone help explain or lead me to what thats called?

If the empty line contains only white space characters, you can remove them using trim() and call isEmpty()

if (lines[i].trim().isEmpty()) {
    continue;
}
Vikdor
  • 23,934
  • 10
  • 61
  • 84