Create a new Java class called AverageWeight. Create two arrays: an array to hold 3 different names and an array to hold their weights. Use Scanner to prompt for their name and weight and store in correct array. Compute and print the average of the weights entered using printf command. Use a loop to traverse and print the elements of each array or use Arrays class method to print. Submit your code.

Respuesta :

Answer:

//import the Scanner class

import java.util.Scanner;

//begin class definition

public class AverageWeight{

       //declare the main method

    public static void main(String []args){

     

       //declare the names array

       String [] names = new String [3];

       

       //declare the weights array

       double [] weights = new double [3];

       

       //Create an object of the Scanner class

       Scanner input = new Scanner(System.in);

       

       

       //create a loop to ask for the names and weights.

       for(int i = 0; i< names.length; i++){

           System.out.println("Enter name " + (i+1));

           names[i] = input.next();

           

           System.out.println("Enter weight " + (i+1));

           weights[i] = input.nextDouble();

           

       }

       

       

       

       //find the sum of the weights

       double sum = 0.0;

       for(int j = 0; j< weights.length; j++){

           sum += weights[j];

           

       }

       

       //find the average

       double average = sum / weights.length;

       

       //print out the average of the weights

       System.out.printf("%s%f \n", "The average of the weights is ", average);

       

       

       //print out the elements of the names array

       System.out.println("Names : ");

       System.out.print("{ ");

       for(int i = 0; i< names.length; i++){

           

           System.out.print(names[i] + " ");

           

       }

       System.out.print(" }");

       

       

       //print out the elements of the weights array

       System.out.println();

       System.out.println();

       System.out.println("Weights : ");

       System.out.print("{ ");

       for(int i = 0; i< weights.length; i++){

           

           System.out.print(weights[i] + " ");

           

       }

       System.out.print(" }");

       

     

    } //end of main method

   

   

} //end of class definition

Sample Output

>> Enter name 1

Peter

>> Enter weight 1

12.0

>> Enter name 2

Joe

>> Enter weight 2

23.4

>> Enter name 3

Paul

>> Enter weight 3

23.9

The average of the weights is 19.766667  

Names :  

{ Peter Joe Paul  }

Weights :  

{ 12.0 23.4 23.9  }

Explanation:

The code contains comments explaining important lines.

The source code file has been attached to this response.

A sample output has also been provided.

Ver imagen stigawithfun