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

1. Write a method product that takes a List as an argument and that returns the

ID: 3542183 • Letter: 1

Question

1. Write a method product that takes a List as an argument and that returns the product of the values in the list. You should use an iterator rather than using calls on get and size. Write a client program to test your product method.


2. Write a method hasNegativeSum that takes a List as a parameter and that returns true if the list has a negative sum and that returns false otherwise. In particular, the method should compute a running sum of values starting with the first value and should determine whether the running sum ever goes negative. For example, if a variable called list stores the following list:(6, 11, -20, 7, 14, 93)then the call hasNegativeSum(list) should return true because the sum of the first three elements is negative (6 + 11 + -20 = -3). If the list had instead stored these values:(6, 15, -20, 7, -4, 5, -9)then hasNegativeSum(list) would return false because even though the list contains some negative numbers, the running sum starting with the first value never goes negative.You are not allowed to call any other methods of the List class to solve this problem. You must solve it using an iterator.Write a client program to test your method.


3. Write a piece of code that inserts a String into an ordered linked list of Strings, maintaining sorted order. For example, for the list (Alpha, Baker, Foxtrot, Tango, Whisky), inserting "Charlie" in order would produce the list:(Alpha, Baker, Charlie, Foxtrot, Tango, Whisky)Note: You cannot use Collections.sort() and your code should be general enough to work with any input string

Explanation / Answer

Code 1



product method


public int product(List<Integer> list){

int multiply = 1;

Iterator<Integer> iterator = list.iterator();

while(iterator.hasNext()) {

multiply = multiply *iterator.next();

}

return multiply;

}



______________________________________________



In case you want the complete code,




import java.util.Iterator;

import java.util.List;

import java.util.ArrayList;


public class CodeOnIterator {

public static void main(String[] args) {

List <Integer> list= new ArrayList<Integer>();

list.add( 1);

list.add( 2);

list.add(5);

list.add(7);

CodeOnIterator code = new CodeOnIterator();

int name = code.product(list);

System.out.println(name);

}

public int product(List<Integer> list){

int multiply = 1;

Iterator<Integer> iterator = list.iterator();

while(iterator.hasNext()) {

multiply = multiply *iterator.next();

}

return multiply;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote