Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a static method called shorten that takes an ArrayList of Integers as a pa

ID: 3644051 • Letter: W

Question

Write a static method called shorten that takes an ArrayList of Integers as a parameter. It should replace each sequence of two or more equal Integers in the ArrayList with a single Integer equal to the sum of the Integers that were equal. For example, suppose that the parameter is an ArrayList named a containing:

[3, 7, 7, 7, 3, 6, 6, 14]

Then after calling shorten the ArrayList a should contain:
[3, 21, 3, 12, 14]

So the 3 occurrences of 7 were replaced with 21, and the 2 occurrences of 6 were replaced with 12. The two occurrences of 3 aren

Explanation / Answer

import java.util.*;

public class sumArray
{
public static void main(String[] args)
{
int[] numArray = new int[8];
ArrayList<Integer> sumList = new ArrayList<Integer>();
int input;
int sum = 0;
Scanner keyboard = new Scanner(System.in);

//input values for the numArray
for (int i = 0; i < numArray.length; i++)
{
System.out.print("Enter value for index " + (i+1) + ": ");
input = keyboard.nextInt();
numArray[i] = input;
}

//Loop through the array to see if any values are the same next to each other
for (int i = 0; i < numArray.length; i++)
{
int num = numArray[i];
if(i == numArray.length - 1)
sumList.add(num);
else if (numArray[i+1] == num)
{
sum = num;
while (numArray[i+1] == num)
{
sum = sum + numArray[i+1];
i++;
if (i == numArray.length - 1)
break;
}
sumList.add(sum);
sum = 0;
}
else
{
sumList.add(num);
}
}
//print the updated sum list
for (int i = 0; i < sumList.size(); i++)
System.out.print(sumList.get(i) + " ");
}
}

In case of doubt ask me.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote