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();...
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,...
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...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to determine if a given string is a palindrome. [A palindrome is a string that reads the same forwards and backwards, for example ‘racecar’, ‘civic’]. Make sure that your method works correctly for special cases, if any. What is the big-O complexity of your method in terms of the list size n. Supplementary Exercise for Programming (Coding) [Stacks] Download and unpack (unzip) the file Stacks.rar....
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT