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

Write a function total_numbers(number_list,weights) that takes a list of numbers

ID: 3808996 • Letter: W

Question

Write a function total_numbers(number_list,weights) that takes a list of numbers and their weights and returns the weighted total of the numbers. Think about what needs to happen before using a loop, during the loop, and after the loop finishes. In this question you are required to use a for loop, and not allowed to use the sum function. If the numbers are [1,2,3] and the weights are [.1,.5,.4] then the weighted total should be 1 * .1 + 2 * .5 + 3 * .4 = 2.3

For example:

Test Result print(round(total_numbers([1,2,3],[.1,.5,.4]),1)) 2.3

Explanation / Answer

WeightedTotal.java :
_________________

import java.util.ArrayList;
import java.util.Scanner;


public class WeightedTotal {
   static int n;
   public static void main(String[] args) {
       Scanner sc= new Scanner(System.in);
       System.out.println("Enter number of elements:");
   n = sc.nextInt();
       ArrayList<Integer> nums = new ArrayList<Integer>();
       ArrayList<Double> weights = new ArrayList<Double>();
       System.out.println("Enter list of "+n +" numbers:");
       for(int i=0;i<n;i++)
           nums.add(sc.nextInt());
       System.out.println("Enter weights of "+n +" numbers:");
       for(int i=0;i<n;i++)
           weights.add(sc.nextDouble());
       double result = total_numbers(nums,weights);
       System.out.printf("%.1f",result);
   }
   public static double total_numbers(ArrayList<Integer> nums,ArrayList<Double> weights){
       double total = 0;
       for(int i=0;i<n;i++){
           total = total + nums.get(i) * weights.get(i);
       }
       return total;
   }
}


Sample Input and Output:
______________________
Enter number of elements:
3
Enter list of 3 numbers:
1 2 3
Enter weights of 3 numbers:
.1 .5 .4
2.3

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