Search code examples
javafor-loopprintln

Java - Print statement in for loop not printing anything


I wrote simple for loop to print the first character from the beginning of the string then first character from the end.. etc, but the print statement doesn't show anything, why?

public class JavaOOP {

    public static void main(String args[]){

        String string = "abca";

        for(int i=0,j=string.length()-1;i<string.length()/2+1 && j>string.length()/2+1;i++,j--){
            System.out.println(string.charAt(i)+ " " + string.charAt(j));
        }
  
    }
}

Solution

  • No need for the loop.

    "... the print statement doesn't show anything, why?"

    This is because the second conditional statement, of the for-loop conditional statement, is never met, thus the loop never iterates.

    j>string.length()/2+1
    

    You can capture the last value using the String#length value.

    Keep in mind, since the characters are referenced using a 0-based index, the last character is going to be the length, minus 1.

    String string = "abca";
    char first = string.charAt(0);
    char last = string.charAt(string.length() - 1);
    
    System.out.println(first + " " + last);
    

    Output

    a a
    

    You could use a loop to capture the first and last character, recursively.

    void traverse(String string) {
        if (string.length() <= 1) return;
        System.out.println(string.charAt(0) + " " + string.charAt(string.length() - 1));
        traverse(string.substring(1, string.length() - 1));
    }
    

    Example output, when string is, "stack overflow".

    s w
    t o
    a l
    c f
    k r
      e
    o v