0

I have to change every 2nd and 3d element in an array I got from the database. The database had 4 columns so these two elements should be taken out of four elements. This is a simpler code to consider:

public void displayNames() {       
String[] array = {"Avon", "Berta", "Chloe", "Derek","Avon", "Berta", "Chloe", "Derek","Avon", "Berta", "Chloe", "Derek"};
        for (int i = 1; i < array.length; i = i + 4) {
            StringBuilder sb = new StringBuilder(array[i]);
                System.out.println(sb.substring(0, 1));
            }
            for (int j = 2; j < array.length; j = j + 4) {
                StringBuilder s = new StringBuilder(array[j]);
                System.out.println(s.substring(0, 1));
            }

As you can see I can extract 2nd and third elements but only using different cycles. My question is how to do it in one cycle? Should I probably use a two-dimensional array or nested loop? Will be grateful for any hint

  • 6
    Do you know how to use the modulo operator, AKA the `%`? – Nexevis Feb 21 '20 at 14:13
  • no, but I'll google for it - thanks for getting a hint! –  Feb 21 '20 at 14:16
  • 3
    @Nexevis *FYI:* The `%` operator is called the **remainder** operator ([JLS 15.17.3](https://docs.oracle.com/javase/specs/jls/se13/html/jls-15.html#jls-15.17.3)). See: [What's the difference between “mod” and “remainder”?](https://stackoverflow.com/q/13683563/5221149) – Andreas Feb 21 '20 at 14:23
  • @Andreas Ah thanks for the info, I blame my teacher from years ago for the misinformation! – Nexevis Feb 21 '20 at 14:25

1 Answers1

1

So you don't want to print: 0,3,4,7,8,11,12,...? That's all the numbers with %4 == 3 or = 0;

public void displayNames() {       
String[] array = {"Avon", "Berta", "Chloe", "Derek","Avon", "Berta", "Chloe", "Derek","Avon", "Berta", "Chloe", "Derek"};
        for (int i = 1; i < array.length; i++) {
            int test = i%4;
            if(test == 0 || test == 3){
                System.out.println(array[i]);
            }
        }
}
vaeng
  • 90
  • 15