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));
}
}
======================================
输入值
3
6
36
61
121
66
26
376
661
6
-1
我需要输出是
3
42
61
121
468
661
6
我的输出
3
6
42
61
121
66
92
468
661
6
我在这里做错了什么?
最佳答案
由于其他人正在尝试(但未能)为您提供有效的解决方案,因此这里带有更改行的注释:
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
}