How do I return an integer that is the sum of the integer values input in an ArrayList for Java at the indices 19, 9, and 14? So far I have:

tmeosky Source

How do I return an integer that is the sum of the integer values input in an ArrayList for Java at the indices 19, 9, and 14? So far I have:
Write a public static method named q3 that takes an ArrayList of Integers as a * parameter and returns an int. The returned int should be the sum of the values int the * input ArrayList at indices 19, 9, and 14. You can assume the input ArrayList has size * large enough to avoid an index out of bounds exception at these indices

public static int q3(ArrayList<Integers>) {     
ArrayList<Integers> thisList = new ArrayList<Integers>();   
thisList.add(9, "3");   
thisList.add(14, "0");  
thisList.add(19, "33");         

int sum = 0;    
int i = 0;
javaarraylist

Answers

answered 4 months ago VINAY DWIVEDI #1

 public static int q3(ArrayList<int> al) {
   int sum = al.get(19) + al.get(9) + al.get(14);
   return sum;
 }

answered 4 months ago lealceldeiro #2

  • Integers is not a valid type, Integer is.
  • Argument passed to methods must have a type and an "identificator" (or whatever you'd like to call it). So, this is wrong: public static int q3(ArrayList<Integers>), and this is correct public static int q3(ArrayList<Integer> nums). In the last one num is the "identificator".
  • ArrayList#add has nothing to do with sum, but with adding new items to the collection. So this (thisList.add(9, "3");) just tries to add the value "3" in the position 9 of the array list thisList.

In order to fix your code you should try:

public static int q3(ArrayList<Integer> nums) { // Integer, not `Integers`
    return nums.get(19) + nums.get(9) + nums.get(14); // assuming the input ArrayList has size * large enough to avoid an index out of bounds exception at these indices
}

comments powered by Disqus