Reputation: 154
package com.company;
import java.util.*;
import java.io.*;
public class Main {
public static int processArray(ArrayList<Integer> array) {
int sum=0;
for (int i=0;i<array.size()-1;i++) {
if (array(i) %2 == 0 && array.get(i+1)%2==0){
sum += array.get(i);
array.set(i,sum);
array.remove(i+1);
i--;
}
}
return array.size();
}
public static void main (String[] args) {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0)
break;
arrayList.add(new Integer(num));
}
int new_length = processArray(arrayList);
for(int i=0; i<new_length; i++)
System.out.println(arrayList.get(i));
}
}
=======================================
Input
3 6 36 61 121 66 26 376 661 6 -1
I need Output to be
3 42 61 121 468 661 6
My Output
3 6 42 61 121 66 92 468 661 6
What am i doing wrong here?
Upvotes: 1
Views: 297
Reputation: 159125
Since others are trying (and failing) to give you working solution, here it is, with comments on changed lines:
public static ArrayList<Integer> processArray(ArrayList<Integer> array) {
for (int i = 0; i < array.size() - 1; i++) { // don't process last value (it has no next value)
if (array.get(i) % 2 == 0 && array.get(i+1) % 2 == 0) {
int sum = array.get(i) + array.get(i+1); // add current and next value
array.set(i, sum); // update current value
array.remove(i+1); // remove next value
i--; // make sure we re-process current value, to compare with "new" next value
}
}
return array; // return modified array
}
Upvotes: 2
Reputation: 520
Try this below code. This will calculate sum of all even index digits entered in arraylist, removes the even indexed digits and you will have the altered list.
import java.util.ArrayList;
import java.util.Scanner;
public class Main1 {
public static int processArray(ArrayList<Integer> array) {
int sum = 0;
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % 2 == 0) {
sum += array.get(i);
array.remove(i);
}
}
return sum;
}
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int num = in.nextInt();
if (num < 0)
break;
arrayList.add(new Integer(num));
}
int sum = processArray(arrayList);
System.out.println("Sum of even index numbers " + sum);
for (int i = 0; i < arrayList.size(); i++)
System.out.println(arrayList.get(i));
}
}
Upvotes: -1