I currently have a working for loop but when I try doing
if(input.substring(i,i++)=="\n")){
space ++;
}
or the same thing with .equals it still never adds one.
Thanks
I currently have a working for loop but when I try doing
if(input.substring(i,i++)=="\n")){
space ++;
}
or the same thing with .equals it still never adds one.
Thanks
For sure you should not use ==
operator. Then I doubt that the equals
does not work.
The crucial point is that "\n" is a char
. Consider this code, then choose the option you preafer
String input = "a\n";
String newLine = System.getProperty("line.separator");
// return 2 because the string contains 2 chars: "a" and "\n"
System.out.println("CharArraysLenIs: " + input.toCharArray().length);
// return true because it compares the strings on char long each
System.out.println("WithEquals_1_Is: " + input.substring(1,2).equals(newLine));
// return true because it compares the strings on char long each
System.out.println("WithEquals_2_Is: " + input.substring(1,2).equals("\n"));
// return false because it copares the location in memory.
// They are really different objects (strings) in the java heap.
System.out.println("WithEqualOperatorIs: " + (input.substring(1,2) == "\n"));
Your code is not correct:
if(input.substring(i,i++)=="\n")){
space ++;
}
returns an empty string because beginIndex and endIndex are equal in your case. This is because i++ will increment i after the variable has been evaluated and used. To make your code work, change i++ to ++i and use equals not ==, or change "\n" to '\n' and substring to charAt:
if(input.substring(i,++i).equals("\n")){
space ++;
}
or
if(input.charAt(i++) == '\n'){
space ++;
}
As mentioned, you shouldn't compare strings with ==
. Furthermore, the pre- and post-incrementing operators are completely wrong here. As @Maxime mentioned in the comment, the i++
increments the value stored in i
. So what is happening is you're taking substring(1,1)
then substring(2,2)
, etc. which all return empty strings of length 0. (Don't believe me? Try it yourself here.)
Since you have a working for-loop, as you mention, you can just use the charAt
method to get the character at the position, and then use ==
to compare the character (not string) to '\n'
.
Eg.
if (input.charAt(i) == '\n') {
space++;
}
private static int countLines(String str){
String[] lines = str.split("\n");
return lines.length-1;
}
This might help you.