It seems that the results of the calculations should be stored in another array so that the sum of the elements at the tail take into original values of the input array a:
// code with debug prints
public static void addNextFourPrint(int... a) {
// print input array
System.out.println(Arrays.toString(a));
int[] b = new int[a.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++) {
sb.append("a[").append(i).append("] = ");
for (int j = 1; j <= 4; j++) {
int k = (i + j) % a.length;
if (j > 1) {
sb.append(" + ");
}
sb.append(a[k]);
b[i] += a[k]; // b[i] = a[i + 1] + ... + a[i + 4]
}
sb.append(" = ").append(b[i]);
System.out.println(sb); // print each element
sb.setLength(0); // clear string builder
}
// print result
System.out.println(Arrays.toString(b));
}
Test
addNextFourPrint(2, 5, 1, 7, 3, 9, 6, 9, 4, 8, 11, 0, 13, 8, 9, 1, 7, 5, 2, 6);
Output
[2, 5, 1, 7, 3, 9, 6, 9, 4, 8, 11, 0, 13, 8, 9, 1, 7, 5, 2, 6]
a[0] = 5 + 1 + 7 + 3 = 16
a[1] = 1 + 7 + 3 + 9 = 20
a[2] = 7 + 3 + 9 + 6 = 25
a[3] = 3 + 9 + 6 + 9 = 27
a[4] = 9 + 6 + 9 + 4 = 28
a[5] = 6 + 9 + 4 + 8 = 27
a[6] = 9 + 4 + 8 + 11 = 32
a[7] = 4 + 8 + 11 + 0 = 23
a[8] = 8 + 11 + 0 + 13 = 32
a[9] = 11 + 0 + 13 + 8 = 32
a[10] = 0 + 13 + 8 + 9 = 30
a[11] = 13 + 8 + 9 + 1 = 31
a[12] = 8 + 9 + 1 + 7 = 25
a[13] = 9 + 1 + 7 + 5 = 22
a[14] = 1 + 7 + 5 + 2 = 15
a[15] = 7 + 5 + 2 + 6 = 20
a[16] = 5 + 2 + 6 + 2 = 15
a[17] = 2 + 6 + 2 + 5 = 15
a[18] = 6 + 2 + 5 + 1 = 14
a[19] = 2 + 5 + 1 + 7 = 15
[16, 20, 25, 27, 28, 27, 32, 23, 32, 32, 30, 31, 25, 22, 15, 20, 15, 15, 14, 15]
A version without debug prints may look as follows (returning modified array):
public static int[] addNextFour(int... a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 1; j <= 4; j++) {
b[i] += a[(i + j) % a.length];
}
System.out.print(b[i] + " ");
}
System.out.println();
return b;
}
Similarly, it can be implemented using Stream API IntStream::range + rangeClosed, IntStream::map, IntStream::peek, IntStream::sum:
public static int[] addNextFourStream(int... a) {
return IntStream.range(0, a.length)
.map(i -> IntStream.rangeClosed(i + 1, i + 4).map(j -> a[j % a.length]).sum())
.peek(x -> System.out.print(x + " "))
.toArray();
}
Test
addNextFour(2, 5, 1, 7, 3, 9, 6, 9, 4, 8, 11, 0, 13, 8, 9, 1, 7, 5, 2, 6);
addNextFourStream(2, 5, 1, 7, 3, 9, 6, 9, 4, 8, 11, 0, 13, 8, 9, 1, 7, 5, 2, 6);
Output
16 20 25 27 28 27 32 23 32 32 30 31 25 22 15 20 15 15 14 15
16 20 25 27 28 27 32 23 32 32 30 31 25 22 15 20 15 15 14 15