Drieke Drieke - 3 months ago 6
Java Question

How do I print just the even or odd chars in an array?

Lets say I have string: 'firetruck'. And I split that string up into the individual letters and put them into an array called T for example. So now T[] looks like {f,i,r,e,t,r,u,c,k}. How can I just print the even chars so my print statement looks like 'frtuk' and the odd looks like 'ierc'. This is what I got so far:

import java.util.Scanner;
import java.util.Arrays;
public class StringFun {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String even_odd = sc.next();
char[] t = even_odd.toCharArray();
System.out.println(Arrays.toString(t));

//I can't get this next part to work.
for(int i = t[0]; i < t.length; i = i + 2){
System.out.println(Arrays.toString(t[i]));
}
}
}

Answer

Just a minor mistake in the code:

You don't need the first value from the array to initialize the loop variable i, just the index value you want the loop to start from.

One tricky thing to keep in mind is that the indexing starts from 0, but we, humans count from 1. (I did a mistake with this in the first edit of the answer too) So the characterss with even ordinals will be printed when the start value is odd.

The start of indexing is quite a common issue one has to constantly keep in mind...

Also, you can print characters directly, you don't need the Arrays.toString() method here:

System.out.println(t[index]);

Is enough.

Odd chars: set i to 0: this will print the 1st, 3rd ... characters

       for(int i = 0; i < t.length; i = i + 2){
            System.out.println(t[i]);
        }

Even chars: set i to 1: this will print the 2nd, 4th ... chars

       for(int i = 1; i < t.length; i = i + 2){
            System.out.println(t[i]);
        }

Eliminating the array

Also, you don't even need to create a char array, you could use String.charAt(int index) for this purpose:

        String even_odd = sc.next();

        for(int i = 0; i < even_odd.length(); i = i + 2){
            System.out.println(even_odd.charAt(i));
        }

Taking it to the next level

Also, to be extra nice, you could extract this into a function, and reuse the functionality:

private static void printChars(String input, boolean even) {
        int i = 0;
        if(even) { //if we need the even chars, start from 1;
          i=1;
        }
        for(; i < input.length(); i = i + 2){
            System.out.println(input.charAt(i));
        }
}

And then your main method would be just this:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String even_odd = sc.next();
        char[] t = even_odd.toCharArray();
        System.out.println(Arrays.toString(t));

        //calling the function for even numbers
        printChars(even_odd, true);

        //calling the function for odd numbers
        printChars(even_odd, false);
    }

Remember duplication is bad. Reuse --> good.