0

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

devfun41
  • 1
  • 2
  • 2
    What is your complete code ? i++ adds one to i and replace the value of i by i+1 are you sure you want to do this ? – Maxime Oct 21 '19 at 15:13

4 Answers4

1

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"));
user2688838
  • 761
  • 5
  • 11
0

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 ++;
}
Andra
  • 1,282
  • 2
  • 11
  • 34
Eirik Moseng
  • 146
  • 5
0

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++;
}
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
-1
private static int countLines(String str){
   String[] lines = str.split("\n");
   return  lines.length-1;
}

This might help you.

Gaurav Dhiman
  • 953
  • 6
  • 11