7.5 Warm up: People\'s weights (Java) (1) Prompt the user to enter five numbers,
ID: 3868602 • Letter: 7
Question
7.5 Warm up: People's weights (Java)
(1) Prompt the user to enter five numbers, being five people's weights. Store the numbers in an array of doubles. Output the array's numbers on one line, each number followed by one space. (2 pts)
Ex:
(2) Also output the total weight, by summing the array's elements. (1 pt)
(3) Also output the average of the array's elements. (1 pt)
(4) Also output the max array element. (2 pts)
Ex:
This is for a Zybooks assignment if anyone is familiar. This is what the starting code looks like and it has to have the return at the end for it to work in this program.
public class Do {
// define the main class
public static void main(String[] args) {
// Create an object for the scanner class
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
double[] m = new double[5];
// Declare and initialize the variables
double weight = 0, avg, max = 0;
// Define for loop
for (int i = 0; i < 5; i++) {
// Prompt the the user to enter weight
System.out.print("Enter Weight" + (i + 1) + ":");
m[i] = sc.nextDouble();
if (max < m[i])
max = m[i];
}
// Display the entered weights
System.out.print("you entered");
// Define for loop
for (int j = 0; j < 5; j++) {
System.out.print(m[j] + " ");
weight = weight + m[j];
}
System.out.println(" ");
avg = weight / 5;
// Display the Total weight
System.out.println("Total weight:" + weight);
// Display the Average weight
System.out.println("Average weight:" + avg);
// Display the maximum weight
System.out.println("Max Weight:" + max);
return;
}
}
Explanation / Answer
Corrected the program with few changes
import java.util.Scanner;
public class HelloWorld
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
double m[]=new double[5];
double weight = 0, avg, max = 0;
int i;
for (i = 0; i < 5; i++)
{
System.out.print("Enter Weight" + (i + 1) + ":");
m[i] = sc.nextDouble();
}
System.out.print("you entered ");
for (i = 0; i < 5; i++)
{
System.out.print(m[i] + " ");
weight = weight + m[i];
}
for (i = 0; i < 5; i++)
{
if(m[i]>max)
max=m[i];
}
System.out.println(" ");
avg = weight / 5;
System.out.println("Total weight:" + weight);
System.out.println("Average weight:" + avg);
System.out.println("Max Weight:" + max);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.