Eric Dants
Eric Dants

Reputation: 31

How can I print a word two letters at a time? - java

The input is supposed to have an even length. The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho. I'm not sure how to make that jump.

public static void twoAtATime(String a) { // School
        int len = a.length();
        if(len%2 == 0) {
            for(int i = 0; i <a.length()/2; i++) {
                    System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
                    System.out.println();
            }
        }

The output is supposed to be like this:

Sc
ho
ol

Upvotes: 0

Views: 569

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38665

To fix it:

  1. Increase i by 2.
  2. Iterate until i < len.

You can improve it:

  1. By calling substring once for two chars.
  2. Using println with param.
  3. Incrementing i once - i += 2.

After improvements:

public static void twoAtATime(String s) {
    int len = s.length();
    if (len % 2 == 0) {
        for (int i = 0; i < len; ) {
            System.out.println(s.substring(i, i += 2));
        }
    }
}

Upvotes: 2

Related Questions