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 =...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems that need to be corrected. Your task is to complete it to course style and documentation standards CS 200 Style Guide. This project will be human graded. This class contains a set of methods. The main method contains some examples of using the methods. Figure out what each method does and style and document it appropriately. The display method is done for you and...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
I need to get the Min and Max value of an array when a user inputs...
I need to get the Min and Max value of an array when a user inputs values into the array. problem is, my Max value is right but my min value is ALWAYS 0. how do i fix this? any help please!!! _________________________________________________________________________________________________ import java.util.Scanner; public class ArrayMenu{ static int count; static Scanner kb = new Scanner(System.in);             public static void main(){ int item=0; int[] numArray=new int[100]; count=0;       while (item !=8){ menu(); item = kb.nextInt();...
To the TwoDArray, add a method called transpose() that generates the transpose of a 2D array...
To the TwoDArray, add a method called transpose() that generates the transpose of a 2D array with the same number of rows and columns (i.e., a square matrix). Add appropriate code in main() of the TwoDArrayApp class to execute the transpose() method and use the display() method to print the transposed matrix. /** * TwoDArray.java */ public class TwoDArray { private int a[][]; private int nRows; public TwoDArray(int maxRows, int maxCols) //constructor { a = new int[maxRows][maxCols]; nRows = 0;...
Write a Java program that asks the user to enter an array of integers in the...
Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 41,...
public class Lab1 { public static void main(String[] args) { int array [] = {10, 20,...
public class Lab1 { public static void main(String[] args) { int array [] = {10, 20, 31, 40, 55, 60, 65525}; System.out.println(findPattern(array)); } private static int findPattern(int[] arr) { for (int i = 0; i < arr.length - 2; i++) { int sum = 0; for (int j = i; j < i + 2; j++) { sum += Math.abs(arr[j] - arr[j + 1]); // finding the difference } if (sum == 20) return i; } return -1; } }...
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)...
I have the following program which returns F(n) for the fibonacci sequence both recursively and iteratively:...
I have the following program which returns F(n) for the fibonacci sequence both recursively and iteratively: public class Fibonacci { //Recursive method public int fibRecursive(int n) { //If n is in the 0th or 1st place return n if (n <= 1) return n; return fibRecursive(n - 1) + fibRecursive(n - 2); } //Iterative method public int fibIterative(int n) { if (n <= 1) return n; int fib = 1, prevFib = 1; for (int i = 2; i <...
Write a Java program that implements a lexical analyzer, lex, a recursive-descent parser, parse, an error...
Write a Java program that implements a lexical analyzer, lex, a recursive-descent parser, parse, an error handling program, error, and a code generator, codegen, for the following EBNF description of a simple assignment statement using an arithmetic expression language. Implement a symbol table by modifying Evaluate class. Modify the stmt() method, Provide an insert() and retrieve() method and store values in symbol table.   Video Help to get started:  https://www.youtube.com/watch?v=-C_S7Lb4kRk&feature=youtu.be import java.io.*; import java.util.*; public class parser { static String inString =...