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)...
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...
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...
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...
Q: Implement an equals method for the ADT list that returns true when the entries in...
Q: Implement an equals method for the ADT list that returns true when the entries in one list equal the entries in a second list. In particular, add this method to the class AList. The following is the method header: public boolean equals (Object other) public class AList<T>{ private T list[]; private int capacity = 100; private int numOfEnteries =0; public AList(){ list = (T[])new Object[capacity + 1]; } public void add(T element){ numOfEnteries++; if (numOfEnteries >capacity) System.out.println ("Exceed limit");...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
question : Take the recursive Java program Levenshtein.java and convert it to the equivalent C program....
question : Take the recursive Java program Levenshtein.java and convert it to the equivalent C program. Tip: You have explicit permission to copy/paste the main method for this question, replacing instances of System.out.println with printf, where appropriate. You can get the assert function from assert.h. Try running the Java program on the CS macOS machines. You can compile and run the program following the instructions discussed in class. Assertions are disabled by default. You can enable assertions by running java...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have this much public class Main { int WIDTH = 0; double HEIGHT = 0; public static void drawSmileyFaces() { System.out.println(" :-):-):-):-):-):-)"); } public static void main (String[] args) { for (int WIDTH = 0; WIDTH < 3; WIDTH++ ) { for(double HEIGHT = 0; HEIGHT < 2; HEIGHT++) { drawSmileyFaces(); } } } } I am pretty sure that alot of this is wrong...