Write a method called runningTotal that returns a new ArrayIntList that contains
ID: 3567739 • Letter: W
Question
Write a method called runningTotal that returns a new ArrayIntList that contains a running total of the original list. In other words, the ith value in the new list should store the sum of elements 0 through i of the original list. For example, given a variable list that stores [2, 3, 5, 4, 7, 15, 20, 7], consider what happens when the following call is made.
ArrayIntList list2 = list.runningTotal();
The varialbe list2 should store [2, 5, 10, 14, 21, 36, 56, 63]. The original list should not be changed by the method. If the original list is empty, the result should be an empty list. The new list should have the same capacity as the original. Remember that there is a list constructor that accepts a capacity as a parameter.
Explanation / Answer
Here you go :)
I've highlighted the method that I added.Please comment if you have any doubts.
public class ArrayIntList {
private int[] elementData;
private int size;
public ArrayIntList() {
elementData = new int[100];
size = 0;
}
public void add(int value) {
elementData[size] = value;
size++;
}
public void remove(int index) {
}
public void add(int index, int value) {
}
public int get(int index) {
return elementData[index];
}
public boolean contains(int value) {
return false;
}
public int indexOf(int value) {
for (int i = 0; i < size; i++) {
if (elementData[i] == value)
return i;
}
return -1;
}
public String toString() {
if (size == 0) {
return "[]";
} else {
String print = "[" + elementData[0];
for (int i = 1; i < size; i++) {
print = print + ", " + elementData[i];
}
print += "]";
return print;
}
}
public int size() {
return size;
}
public ArrayIntList runningTotal()
{
//creating a new ArrayIntList
ArrayIntList list=new ArrayIntList();
//initializing a new variable sum
int sum=0;
for(int i=0;i<this.size();i++)
{
//getting the cumulative sum till now
sum+=this.get(i);
//adding the sum till now to the ArrayInList
list.add(sum);
}
//returning the list
return list;
}
public static void main(String[] args)
{
//constructor for creating new ArrayIntList
ArrayIntList list=new ArrayIntList();
//Adding some elements to the arraylist
list.add(2);
list.add(3);
list.add(5);
list.add(4);
list.add(7);
list.add(15);
list.add(20);
list.add(7);
//printing the list
System.out.println(list.toString());
//creating new arraylist
ArrayIntList list2=new ArrayIntList();
//calling the runningTotal method
list2=list.runningTotal();
//printing the second array
System.out.println(list2.toString());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.