Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need a check in this code to make sure the user is entering a number and not a letter. Thank you for your help!

I need a check in this code to make sure the user is entering a number and not a letter. Thank you for your help!

package weightedavgdropsmallest; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;

public class WeightedAvgDropSmallest { public static ArrayList input() { Scanner in = new Scanner(System.in); System.out.println("Enter 5 to 10 numbers, separated by spaces:"); String[] numbers = in.nextLine().split(" "); ArrayList arr = new ArrayList(); for(int i = 0; i < numbers.length; i++){ arr.add(Double.parseDouble(numbers[i])); } return arr; } public static int numbersDropped() { Scanner in = new Scanner(System.in); System.out.print("Enter how many of the lowest values to drop: "); int numbers = in.nextInt(); return numbers; } public static double getWeight() { Scanner in = new Scanner(System.in); System.out.print("Enter the weight: "); double numbers = in.nextDouble(); return numbers; } public static double weightedMean(ArrayList arr, int drop, double weight) { Collections.sort(arr, Collections.reverseOrder()); double avg = 0; for(int i = 0; i < arr.size() - drop; i++){ avg += weight * arr.get(i); } return avg / (arr.size() - drop); } public static void print(ArrayList arr, int drop, double weight, double avg) { System.out.print("Given the numbers: "); for(int i = 0; i < arr.size(); i++){ System.out.printf("%.2f,", arr.get(i)); if(i == arr.size() - 2) System.out.printf(" and "); } System.out.println("and using a weight of " + weight + ", the weighted average of all the numbers except the lowest " + drop + " numbers is "); System.out.printf("%.2f", avg); System.out.println(); } public static void main(String args[]) { ArrayList arrayList = input(); int drop = numbersDropped(); double weight = getWeight(); double mean = weightedMean(arrayList, drop, weight); print(arrayList, drop, weight, mean); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

DB2 11 The Ultimate Database For Cloud Analytics And Mobile

Authors: John Campbell, Chris Crone, Gareth Jones, Surekha Parekh, Jay Yothers

1st Edition

1583474013, 978-1583474013

More Books

Students also viewed these Databases questions