Java - Print statement in for loop not printing anything

95 views Asked by At

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));
        }
  
    }
}
3

There are 3 answers

0
Reilas On BEST ANSWER

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
3
Supreet T On

Notice that j starts at 3 and the condition checks while j is greater than 3 in this case, so the loop won't run.

Also notice that the two conditions can be simplified to i <= j.

abcd:
a d
b c

abcde:
a e
b d
c c
public class JavaOOP {
    public static void main(String[] args) {
        String string = "abcd";

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

You don't even need two variables:

String input = /* some input */;
int len = input.length();
for (int i = 0; i < len / 2; i++) {
    System.out.println(input.charAt(i) + " " + input.charAt(len - 1 - i));
}
if (len % 2 == 1) { //account for middle character in odd-length string
    System.out.println(" " + input.charAt(len / 2)); //spaces it "in the middle"
}

In essence, you're using the symmetry of the String. You need characters the same distance from the ends of the strings (at indices 0 and input.length() - 1). So i is your distance from the ends, calculated as and simplified from 0 + i and input.length() - 1 - i.

This results in (without repeating the characters in an odd-length string):

Input: abcde
a e
b d
 c

Input: abcdef
a f
b e
c d