Question

In: Computer Science

WRITE A JAVA PROGRAM: For this lab, you will create a 3 x 7 two dimensional...

WRITE A JAVA PROGRAM:

For this lab, you will create a 3 x 7 two dimensional array to store how many pounds of food three monkeys eats each day in a week. The 2D array is then passed to functions to find total, average and least amount of food consumption, etc. The program then need to display:

  • the average amount of food the three monkeys ate per day

  • the least amount of food eaten all week by any one monkey.

  • each monkey's consumption of food during the week

  • the average of food the 3 monkeys ate on Monday and Saturday.

The general structure of Lab9.java should be similar as follows:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Lab9
{
    public static void main(String[] args)
    {
        //declare necessary constants and variables here
        //......

        //Create a 2D array to hold the pounds of food consumed
        //by each monkey on each day of the week
        //......

        //Use nested for loop to get data and fill in the 2D array
        //......

        //call the findGroupTotal() method and compute
        //the average amount of food the 3 monkeys ate per day
        //......

//call the findLeastAmtFood() method and compute
//the least amount of food eaten all week by any one monkey
//......

         //Find Monkey #1 total consumption of food during the week
        //......

        //Find Monkey #2 total consumption of food during the week
        //......

        //Find Monkey #3 total consumption of food during the week
        //......

        //Find the average of food the 3 monkeys eat on Monday
        //......

        //Find the average of food the 3 monkeys eat on Saturday
        //......
    } //end main()

    //This method takes a 2D array as input parameter and returns
    //the sum of all elements inside
    public static double findGroupTotal(double[][] a2DArray)
    {
        //......
    }

//This method takes a 2D array as input parameter and returns
//the smallest element inside
public static double findLeastAmtFood(double[][] a2DArray)
{
    //......
}

} //end of class

1.2 Step 2: Declare necessary variables, constants and a 2D array inside the main()

For this section of the lab, you will need to declare two (2) constants, both are integers, one for the number of monkeys (3), another for the number of days (7). You also need to declare a Scanner object that is used to read data from the user, and also a DecimalFormat object which will be used to format all double variables' output. Note: in this lab, all output need to be formatted with 2 decimal digits.

// For example, declare a constant that hold the number of monkeys.
final int NUM_MONKEYS = 3;

// declare a constant that hold the number of days (7 days).
// ----

// declare a Scanner object which will be used to get user input
// ----

// declare a DecimalFormat object which will be used to format the output
// ----

// declare and create a 2D array called 'food' that holds the pounds of food consumed
// by each monkey on each day of the week

// ----

As we learned in class, for example, to declare and create a two dimensional array, the syntax is as follows.

data_type[][] ArrayName = new data_type[NUM_OF_ROWS][NUM_OF_COLUMNS];

For Lab9, the data type is the pounds of food each monkey ate on a specific day; ArrayName as mentioned above, is food, the number of rows corresponds to number of the monkeys, and the number of columns corresponds to number of days in a week.

1.3 Step 3: Read in data from user and fill in the 2D array

Next, use the Scanner object created in the previous step to ask the user to enter the pounds of food ate by each of the 3 monkeys in each day of the week. i.e. we will need to fill in the 2D array 'food' we created in the previous step row-by-row, and for each row, we need to fill in the data from left to right. Remeber that we should always print a message indicating what is to be input before requesting information from the user. To do this task, we will need to write a nested for loop, the outer for loop iterates on each of the monkeys, where the inner for loop iterates on each of the day in one week.

for (/* loop logic - iterate on each of the 3 monkeys */)
{
    System.out.print("\nEnter pounds of food eaten by monkey #" + //---- + " on \n");
    for (/*loop logic - iterate on each day of the week */)
        {
        System.out.print( " on day " + //---- + ": ");
        //use Scanner object to get user input and store it inside 2D array 'food'
        food[monkey][day] = scan.nextDouble();
        }
}

//Codes in step #6 to step #8 continue......

1.4 Step 4: Design the findGroupTotal() method

Up to above step 3, codes should be put inside the main() method. In order to call findGroupTotal() method in main(), we need to design findGroupTotal() first. This method need to be put outside of the main(), but within the same class. The header of the method is as follows:

public static double findGroupTotal(double[][] a2DArray)

Basically this method takes a two dimensional array as input and returns the sum of all its elements inside. As we learned in class, in order to do this, we will need to write a nested for loop, the outer for loop iterates on each of the rows, where the inner for loop iterates on each of the columns of the 2D array. Very similar as we did in step #3. Note:

  • a2DArray.length equals to the number of rows
  • a2DArray[0].length equals to the number of columns.

double total = 0.0;

for (/* loop logic - iterate on each of the row */)
{
    for (/* loop logic - iterate on each of the colunms */)    
        total += a2DArray[row][column];
}
return total;

1.5 Step 5: Design the findLeastAmtFood() method

Similar as we did in step #4, in order to call findLeastAmtFood() method in main(), we need to design findLeastAmtFood() method first. This method need to be put outside of the main(), but inside the Lab9.java class. The header of the method is as follows:

public static double findLeastAmtFood(double[][] a2DArray)

Basically this method takes a two dimensional array as input and returns the smallest elements inside. As we learned in class, in order to do this, we will need to write a nested for loop, the outer for loop iterates on each of the rows, where the inner for loop iterates on each of the columns of the 2D array. Very similar as we did in step #4, except that we need to declare and intialize a local variable leastAmt as follows:

double leastAmt = a2DArray[0][0];

for (/* loop logic - iterates on each of the rows */)
{
    for (/* loop logic - iterate on each of the columns */)
        {
        if (a2DArray[row][column] < leastAmt)
            //replace leastAmt with the two-D array element at (row, column)
        }

}
return leastAmt;

1.6 Step 6: Call findGroupTotal()and findLeastAmtFood() methods in main()

Continue on what we have left in step 4, now we need to call findGroupTotal() and  findLeastAmtFood() methods on the two-dimensional array food. Since both method returns a double value, you might need to declare any necessary variables to hold the returned value, such as the following:

double groupTotal;

When we call a method with 2D array as input parameter, we just need to plug in the actual parameter's name, such as the following:

groupTotal = findGroupTotal(food);    //find total on 2D array food

Next, you need to do simple computation to find the average amount of food ate per day by the entire family of monkeys, which equals to the groupTotal divided by number of days, then output the computation result according to the test cases.

Similarly, call findLeastAmtFood()method on two dimensional array food, declare any necessary local variables here and output the result as test cases show.

1.7 Step 7: Find each of the monkey's consumption of food during the week

Still inside the main() method, for 2D array food, we need to find the sum of each of the rows, this corresponds to each of the monkeys' consumption of food in the whole week. Use monkey #1 as an example, first we declare a local variable totalOne which will be used to hold monkey #1's total consumption,

double totalOne = 0.0;

Next, we write a for loop which iterates on each of the days in a week (column of 2D array food) and sum the elements one-by-one as follows:

for (int day = 0; day < NUM_DAYS; day++)
    totalOne += food[0][day];

we then output the result on screen:

System.out.print("\nMonkey #1 eat total of " + fmt.format(totalOne) + " pounds of food in this week.\n");

//Follow above monkey #1's example, compute and output monkey #2 & #3's total consumption of food in one week

//----

1.8 Step 8: Find the average of food the 3 monkeys eat on Monday and Saturday

Continue on above step 7, we now need to find the total amount of food the 3 monkeys ate on Monday or Saturday, this corresponds to sum of all elements in column 0 and 5 of 2D array food respectively. Always keep in mind that index starts from 0!

Let's compute the average of food the three monkeys ate on Monday first, we declare a local variable totalMonday which will be used to hold the total consumption, on Monday

double totalMonday = 0.0;

Next, we need to write a for loop which iterates on each of the monkeys on Monday (row of 2D array food), note for Monday, the column index is 0,

for (int monkey = 0; monkey < 3; monkey ++)
        totalMonday += food[monkey][0];

Last, we compute the average and output accordingly,

double averageMon = totalMonday / 3.0;

//Follow above Monday example, compute and output the average of food the three monkeys consumed on Saturday.

//----

Solutions

Expert Solution

/*********************************Lab9.java**************************/

import java.text.DecimalFormat;
import java.util.Scanner;

public class Lab9 {
   public static void main(String[] args) {

       // declare necessary constants and variables here
       final int NUM_MONKEYS = 3;
       final int NUM_OF_DAYS = 7;

       double groupTotal, avgAmountOfFood;
       double leastAmountOfFood;
       Scanner scan = new Scanner(System.in);

       DecimalFormat fmt = new DecimalFormat("##.00");

       double[][] food = new double[NUM_MONKEYS][NUM_OF_DAYS];

       // Create a 2D array to hold the pounds of food consumed
       // by each monkey on each day of the week
       for (int monkey = 0; monkey < NUM_MONKEYS; monkey++) {
           System.out.print("\nEnter pounds of food eaten by monkey #" + (monkey + 1) + "\n");
           for (int day = 0; day < NUM_OF_DAYS; day++) {
               System.out.print(" on day " + (day + 1) + ": ");
               // use Scanner object to get user input and store it inside 2D array 'food'
               food[monkey][day] = scan.nextDouble();
           }
       }

       // Use nested for loop to get data and fill in the 2D array

       // call the findGroupTotal() method and compute

       groupTotal = findGroupTotal(food);

       // the average amount of food the 3 monkeys ate per day

       avgAmountOfFood = groupTotal / 7.0;
       // call the findLeastAmtFood() method and compute
       System.out.println("\nAverage amount of food eaten by all the monkeys " + fmt.format(avgAmountOfFood));
       // the least amount of food eaten all week by any one monkey

       leastAmountOfFood = findLeastAmtFood(food);

       System.out.println("Least amount of food eaten by monkey: " + fmt.format(leastAmountOfFood));
       // Find Monkey #1 total consumption of food during the week
       double totalOne = 0.0;

       for (int day = 0; day < NUM_OF_DAYS; day++)
           totalOne += food[0][day];

       System.out.print("\nMonkey #1 eat total of " + fmt.format(totalOne) + " pounds of food in this week.\n");
       // Find Monkey #2 total consumption of food during the week

       double totalTwo = 0.0;

       for (int day = 0; day < NUM_OF_DAYS; day++)
           totalTwo += food[1][day];

       System.out.print("\nMonkey #2 eat total of " + fmt.format(totalTwo) + " pounds of food in this week.\n");
       // Find Monkey #3 total consumption of food during the week

       double totalThree = 0.0;

       for (int day = 0; day < NUM_OF_DAYS; day++)
           totalThree += food[2][day];

       System.out.print("\nMonkey #3 eat total of " + fmt.format(totalThree) + " pounds of food in this week.\n");
       // Find the average of food the 3 monkeys eat on Monday

       double totalMonday = 0.0;
       for (int monkey = 0; monkey < 3; monkey++)
           totalMonday += food[monkey][0];

       double averageMon = totalMonday / 3.0;

       System.out.println("\nMonkeys eat average of " + fmt.format(averageMon) + " pounds of food on monday\n");
       // Find the average of food the 3 monkeys eat on Saturday
       double totalSaturday = 0.0;
       for (int monkey = 0; monkey < 3; monkey++)
           totalSaturday += food[monkey][5];

       double averageSat = totalSaturday / 3.0;
       System.out.println("\nMonkeys eat average of " + fmt.format(averageSat) + " pounds of food on Saturday\n");

       scan.close();
   } // end main()

   // This method takes a 2D array as input parameter and returns
   // the sum of all elements inside
   public static double findGroupTotal(double[][] a2DArray) {

       double total = 0.0;

       for (int row = 0; row < a2DArray.length; row++) {
           for (int column = 0; column < a2DArray[0].length; column++)
               total += a2DArray[row][column];
       }
       return total;
   }

   // This method takes a 2D array as input parameter and returns
   // the smallest element inside
   public static double findLeastAmtFood(double[][] a2DArray) {

       double leastAmt = a2DArray[0][0];

       for (int row = 0; row < a2DArray.length; row++) {
           for (int column = 0; column < a2DArray[0].length; column++) {
               if (a2DArray[row][column] < leastAmt)

                   leastAmt = a2DArray[row][column];
           }

       }
       return leastAmt;
   }

}

/**********************output********************/


Enter pounds of food eaten by monkey #1
on day 1: 2
on day 2: 3
on day 3: 4
on day 4: 5
on day 5: 6
on day 6: 3
on day 7: 4

Enter pounds of food eaten by monkey #2
on day 1: 53
on day 2: 34
on day 3: 3
on day 4: 4
on day 5: 5
on day 6: 6
on day 7: 4
3
Enter pounds of food eaten by monkey #3
on day 1: 5
on day 2: 6
on day 3: 6
on day 4: 5
on day 5: 4
on day 6: 43
on day 7: 5

Average amount of food eaten by all the monkeys 34.29
Least amount of food eaten by monkey: 2.00

Monkey #1 eat total of 27.00 pounds of food in this week.

Monkey #2 eat total of 109.00 pounds of food in this week.

Monkey #3 eat total of 104.00 pounds of food in this week.

Monkeys eat average of 30.00 pounds of food on monday


Monkeys eat average of 4.33 pounds of food on Saturday

Please let me know if you have any doubt or modify the answer, Thanks :)

Console X <terminated > Lab9 [Java Application] C:\Program Files\Java\jre 1.8.0_231\bin\javaw.exe (1 Enter pounds of food eaten by monkey #1 on day 1: 2 on day 2: 3 on day 3: 4. on day 4: 5 on day 5: 6 on day 6: 30 on day 7: 4 Enter pounds of food eaten by monkey #2 on day 1: 53 on day 2: 34 on day 3: 3 on day 4: 4 on day 5: 5 on day 6: 6 on day 7: 4 Enter pounds of food eaten by monkey #3 on day 1: 5 on day 2: 6 on day 3: 6 on day 4: 5 on day 5: 4 on day 6: 43 on day 7: 5 Average amount of food eaten by all the monkeys 34.29 Least amount of food eaten by monkey: 2.00 Monkey #1 eat total of 27.00 pounds of food in this week. Monkey #2 eat total of 109.00 pounds of food in this week. Monkey #3 eat total of 104.00 pounds of food in this week. Monkevs eat average of 30.00 pounds of food on mondav


Related Solutions

Write a program in Java to do the following: -Create a one-dimensional array of 7 integers...
Write a program in Java to do the following: -Create a one-dimensional array of 7 integers as follows: Assign {35,20,-43,-10,6,7,13} -Create a one dimensional array of 7 Boolean values as follows: Assign {true,false,false,true,false,true,false} -Create a one dimensional array of 7 floating-point values as follows: Assign {12.0f,1.5f,-3.5f,-2.54f,3.4f,45.34f,22.13f} -Declare sum as integer and set it to 0. -Declare sumf as float and set it to 0.0f. -Use a for loop to go through each element of the Boolean array, and if an...
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: Create a method to fill the 2-dimensional array with (random numbers, range 0 - 30). The array has rows (ROW) and columns (COL), where ROW and COL are class constants. Create a method to print the array. Create a method to find the largest element in the array Create a method to find the smallest element in the array Create a method to...
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: 1. Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. 2. Create a method to print the array. 3. Create a method to find the largest element in the array 4. Create a method to find the smallest element in the array 5....
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. Create a method to print the array. Create a method to find the largest element in the array Create a method to find the smallest element in the array Create a method to find...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your...
IN JAVA Write a program that uses a two-dimensional array to store the highest and lowest...
IN JAVA Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. Prompt the user for 12 months of highest and lowest.   Write two methods : one to calculate and return the average high and one to calculate and return the average low of the year. Your program should output all the values in the array and then output the average high and the average low. im trying to...
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test...
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test data. The program should have the following functions: getTotal - This function should accept two-dimensional array as its argument and return the total of all the values in the array. getAverage - This function should accept a two-dimensional array as its argument and return the average of values in the array. getRowTotal - This function should accept a two-dimensional array as its first argument...
Write a Java program that will use a two-dimensional array to solve the following tasks: 1....
Write a Java program that will use a two-dimensional array to solve the following tasks: 1. Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. 2. Create a method to print the array. 3. Create a method to find the largest element in the array 4. Create a method to find the smallest element in the array 5. Create a...
• This lab, you will write a Java program to determine if a given Sudoku puzzle...
• This lab, you will write a Java program to determine if a given Sudoku puzzle is valid or not. • You determine if the puzzle is complete and valid, incomplete, or is invalid. • A puzzle is a 2-dimensional array 9x9 array. Each element contains the numbers 1 – 9. A space may also contain a 0 (zero), which means the spot is blank. • If you don’t know how a Sudoku Puzzle works, do some research, or download...
3) Create a Java program that uses NO methods, but use scanner: Write a program where...
3) Create a Java program that uses NO methods, but use scanner: Write a program where you will enter the flying distance from one continent to another, you will take the plane in one country, then you will enter miles per gallon and price of gallon and in the end it will calculate how much gas was spend for that distance in miles. Steps: 1) Prompt user to enter the name of country that you are 2) Declare variable to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT