Design and implement a Java program for programming exercise 8.1, page 305 (name
ID: 3684559 • Letter: D
Question
Design and implement a Java program for programming exercise 8.1, page 305 (name it SumArrayColumns) as described in the problem statement. Write method sumColumn() as specified. To test this method, the main method of your program prompts the user to enter a 3-by-4 matrix and displays the sum of each column (by calling method sumColumns()). Design the main method of your program such that it allows the user to re-run the program with different inputs (i.e., use a loop). Document your code, and organize and space the outputs properly. Use escape characters and formatting objects when applicable. Here is the program from the textbook the question is referring to when applicable.
Explanation / Answer
import java.util.*;
public class SumofColumn
{
public static void main(String args[])
{
double[][] k = createArray();
int i = 0;
double sum = sumColumn(k, i);
System.out.println("Sum of the elements at column " + i + " is " + sum);
}
public static double[][] createArray()
{
Scanner input = new Scanner(System.in);
double[][] k = new double[3][4];
System.out.println("Enter a " + k.length + "-by-" + k[0].length + " matrix row by row: ");
for (int i = 0; i < k.length; i++)
for (int j = 0; j < k[0].length; j++)
k[i][j] = input.nextDouble();
return k;
}
public static double sumColumn(double[][] k, int columnIndex)
{
double tot = 0.0;
for (int i = 0; i < k.length; i++)
{
for (int j = 0; j < k[i].length; j++) {
tot+= k[i][j];
}
}
return tot;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.