Question

Write a method that returns the sum of all the elements in a specified column in...

Write a method that returns the sum of all the elements in a specified column in a 3 x 4 matrix using the following header:

public static double sumColumn(double[][] m, int columnIndex)

The program should be broken down into methods, menu-driven, and check for proper input, etc.

The problem I'm having is I'm trying to get my menu to execute the runProgram method. I'm not sure what should be in the parentheses to direct choice "1" to the method. I'm sure I'll also have that problem with executing choice "2," which should go to the sumColumn method, but I'm not there yet. I'll also need a test method. I'd appreciate any help. Here's my code:

package sumelements;

import java.util.Scanner;
public class SumElements
{

private final static Scanner myScan = new Scanner(System.in);

  
//=================void main=====================================================
public static void main(String[] args)
{
char choice;
  
do
{
choice = GetMenu();
switch(choice)
{
case '1':
{
runProgram();
break;
}
case '2':
{
  
break;
}
case '3':
{
System.out.println("Thanks for using ACME products.\n");
break;
}
default:
{
System.out.println("Invalid input. Please re-enter.\n");
choice = GetMenu();
}
}
}while(choice != '3');
}
  
//===============GetMenu=========================================================
private static char GetMenu()
{
System.out.print("=================================\n"
+ " Acme Element Adder \n"
+ "\t(1) Input a 3 x 4 matrix \n "
+ "\t(2) Test system with random number \n"
+ "\t(3) Quit the program\n"
+ "\t Make your choice: ");
  
char choice = myScan.next().toUpperCase().charAt(0);
return choice;
}
  
public static void runProgram();
{
double arr[][]=new double[3][4];

System.out.println("Enter a 3-by-4 matrix row by row: ");

for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
arr[i][j]=myScan.nextDouble();
}
}

for(int i=0;i<4;i++)
{
System.out.println("Sum of the element at column "+i+" is "+sumColumn(arr,i));
}
}

public static double sumColumn(double[][]m,int ColumnIndex)
{
double sum=0;

for(int i=0;i<3;i++)
{
sum+=m[i][ColumnIndex];
}
  
return sum;
}
}

Homework Answers

Answer #1

JAVA CODE:

import java.util.*;

public class SumElements {

    // Scanner

    private final static Scanner myScan = new Scanner(System.in);

    public static void main(String[] args){

        // Declare int variable for choice

        int choice;

        while(true){

            // calling GetMenu() function get the choice

            choice = GetMenu();

            // enter choice in the switch case

            switch(choice)

            {

                case 1:

                {

                    // calling runProgram() function

                    runProgram();

                    break;

                }

                case 2:

                {  

                    // calling runProgramRandomNumber() function

                    runProgramRandomNumber();

                    break;

                }

                case 3:

                {   // Display the message

                    System.out.println("Thanks for using ACME products.\n");

                    return;// exit program

                }

                default:

                {   // display message for invalid choice

                    System.out.println("Invalid input. Please re-enter.\n");

                }

            }

        }   

    }

    // Define GetMenu() method

    // This method take the choice from the user

    private static int GetMenu()

    {

        System.out.print("\n=================================\n"

                          + " Acme Element Adder \n"

                          + "\t(1) Input a 3 x 4 matrix \n "

                          + "\t(2) Test system with random number \n"

                          + "\t(3) Quit the program\n"

                          + "\t Make your choice: ");

        // ask for input choice

        int choice = myScan.nextInt();

        return choice;// return choice

    }

    // Define runProgram() method

    public static void runProgram()

    {

        // Declare double 3 x 4 array

        double arr[][]=new double[3][4];

        System.out.println("Enter a 3-by-4 matrix row by row: ");

        // Enter the element

        for(int i=0;i<3;i++)

        {

            for(int j=0;j<4;j++)

            {

                arr[i][j]=myScan.nextDouble();

            }

        }

        // iterate for loop for Sum of the element at column

        for(int i=0;i<4;i++)

        {

            // calling sumColumn() method and display

            System.out.println("Sum of the element at column "+i+" is "+sumColumn(arr,i));

        }

    }

    // Define runProgramRandomNumber() method

    public static void runProgramRandomNumber()

    {

        // Declare double 3 x 4 array

        double arr[][]=new double[3][4];

        System.out.println("Generating random number 3-by-4 matrix : ");

        // Random number object

        Random rand = new Random();

        for(int i=0;i<3;i++)

        {

            for(int j=0;j<4;j++)

            {   // generate random number and them insert into matrix

                arr[i][j]=rand.nextInt(10);

            }

        }

        // Display the 3 x 4 matrix

        for(int i=0;i<3;i++)

        {

            for(int j=0;j<4;j++)

            {

                System.out.print((int)arr[i][j]+" ");

            }

            System.out.println();

        }

        // Iterate for loop

        for(int i=0;i<4;i++)

        {

            // calling sumColumn() method and display

            System.out.println("Sum of the element at column "+i+" is "+sumColumn(arr,i));

        }

    }

    // Define sumColumn() method

    // pass the parameter 3 x 4 metrix and ColumnIndex

    public static double sumColumn(double[][]m,int ColumnIndex)

    {

        // Declare sum variable

        double sum=0;

        for(int i=0;i<3;i++)

        {

            // calculate the sum of specific column

            sum+=m[i][ColumnIndex];

        }

        // return sum

        return sum;

    }

}

OUTPUT:

NOTE: If you don't understand any step please tell me.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
Write a loop that sets each array element to the sum of itself and the next...
Write a loop that sets each array element to the sum of itself and the next element, except for the last element which stays the same. Be careful not to index beyond the last element. Ex: Initial Scores: 10, 20, 30, 40 Scores after loop: 30, 50, 70, 40 Import. java.util.Scanner; public class StudentScores { public static void main (String [] args){ Scanner scnr = new Scanner (System.in); final int SCORES_SIZE = 4; int [] bonusScores = new int[SCORES_SIZE]; int...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
Design a program that calculates the amount of money a person would earn over a period...
Design a program that calculates the amount of money a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing what salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){    strName = " ";    strSalary = "$0";    } public Employee(String Name, String Salary){    strName = Name;    strSalary = Salary;    } public void setName(String Name){    strName = Name;    } public void setSalary(String Salary){    strSalary = Salary;    } public String getName(){    return strName;    } public String getSalary(){    return strSalary;    } public String...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
JAVA please Arrays are a very powerful data structure with which you must become very familiar....
JAVA please Arrays are a very powerful data structure with which you must become very familiar. Arrays hold more than one object. The objects must be of the same type. If the array is an integer array then all the objects in the array must be integers. The object in the array is associated with an integer index which can be used to locate the object. The first object of the array has index 0. There are many problems where...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT