In: Computer Science
Java, no imports:
Given a list of integers, round each number to the nearest
multiple of 5.
2.5-7.49 round to 5. 7.5-12.49
round to 10. 12.5-17.49 round to 15. etc.
return the sum of all the rounded
elements.
Implement this way for
credit:
Fill in the method directly below
this one called helperRound() to round each number.
Call that method and use the sum of the returned values.
helperSum({4.3, 16.7}) returns
20
helperSum({25.7, 21.2, 27.5})
returns 75
helperSum({2.5}) returns 5
helperSum({2.49, 12.49, 40.2,
42.5}) returns 95
@param nums is an arrayList of
doubles
@return the sum of the all elements
after rounding
*/
public static int helperSum(ArrayList<Double> nums)
{
int sum = 0;
return sum;
}//end helperSum
/**
Method HelperRound will round
a number up or down to the nearest 5.
@param num double
number,
@return the rounded up or
down number to the nearest multiple of 5.
*/
public static int helperRound(double n){
int rounded =
0;
return
rounded;
}//end HelperRound
Program Code Screenshot
Sample Output
Program Code to Copy
import java.util.ArrayList; import java.util.Arrays; class Main{ public static int helperSum(ArrayList<Double> nums) { int sum = 0; //Loop through all elements in the array for(double x : nums){ //Find sum of helperRounds sum += helperRound(x); } return sum; }//end helperSum /** Method HelperRound will round a number up or down to the nearest 5. @param n double number, @return the rounded up or down number to the nearest multiple of 5. */ public static int helperRound(double n){ //l5 and r5 are the nearest multiples of 5 on either side int l5 = (int)n; while(l5%5!=0){ l5--; } int r5 = (int)n; //Check the closest l5, or r5 while(r5%5!=0){ r5++; } if(n-l5<r5-n){ return l5; } return r5; }//end HelperRound public static void main(String[] args) { double d[] = {4.3,16.7}; ArrayList<Double> list = new ArrayList<>(); for(double x : d){ list.add(x); } System.out.println(Arrays.toString(d)+" : "+helperSum(list)); d = new double[]{25.7, 21.2, 27.5}; list = new ArrayList<>(); for(double x : d){ list.add(x); } System.out.println(Arrays.toString(d)+" : "+helperSum(list)); d = new double[]{2.5}; list = new ArrayList<>(); for(double x : d){ list.add(x); } System.out.println(Arrays.toString(d)+" : "+helperSum(list)); d = new double[]{2.49, 12.49, 40.2, 42.5}; list = new ArrayList<>(); for(double x : d){ list.add(x); } System.out.println(Arrays.toString(d)+" : "+helperSum(list)); } }