I need to create a 2 Dimension Array, it needs to do the following. 1, it needs
ID: 3638893 • Letter: I
Question
I need to create a 2 Dimension Array, it needs to do the following.1, it needs to be a customized array (you create the amount of rows and columns)
2, it needs a method called getTotal, that accepts the 2d array and return the values of all the numbers in the array, (1+2+3+4+5+6; getTotal=15)
3, it needs a method called getAverage " " and return the average of the array
4, it needs a method called getRowTotal and returns (reports) the total of each row
5, it needs a method called getColumnTotal, returns the total of each column
6,it needs a method called getHighestInRow, returns the highest value and reports which row it is in
7,it needs a method called getLowestInRow, returns the lowest value and reports which row it is in
Explanation / Answer
please rate - thanks
import java.util.*;
public class matrix718
{
public static void main(String[] args)
{Scanner in = new Scanner(System.in);
int n,i,j;
System.out.print("Enter size of matrix: ");
n=in.nextInt();
while(n<2)
{System.out.println("size must be at least 2");
System.out.print("Enter size of matrix: ");
n=in.nextInt();
}
int [][] a = new int [n][n];
Random r=new Random();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
a[i][j]=r.nextInt(500);
}
System.out.println("The Matrix:");
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
System.out.print(a[i][j]+" ");
System.out.println(" ");
}
System.out.println("The total of all elements is "+getTotal(a));
System.out.println("The average of all elements is "+getAverage(a));
System.out.println("The total of all elements in row 3 is "+getRowTotal(a,3));
System.out.println("The total of all elements in column 3 is "+getColumnTotal(a,3));
System.out.println("The highest element in row 3 is "+getHighestInRow(a,3));
System.out.println("The lowest element in column 3 is "+getLowestInRow(a,3));
}
public static int getTotal(int a[][])
{int i,j,tot=0;
for(i=0;i<a.length;i++)
for(j=0;j<a[0].length;j++)
tot+=a[i][j];
return tot;
}
public static double getAverage(int a[][])
{return (double)getTotal(a)/(a.length*a[0].length);
}
public static int getRowTotal(int a[][],int n)
{int j,tot=0;
for(j=0;j<a[0].length;j++)
tot+=a[n][j];
return tot;
}
public static int getHighestInRow(int a[][],int n)
{int j,max=a[n][0];
for(j=0;j<a[0].length;j++)
if(a[n][j]>max)
max=a[n][j];
return max;
}
public static int getLowestInRow(int a[][],int n)
{int j,low=a[n][0];
for(j=0;j<a[0].length;j++)
if(a[n][j]<low)
low=a[n][j];
return low;
}
public static int getColumnTotal(int a[][],int n)
{int j,tot=0;
for(j=0;j<a.length;j++)
tot+=a[j][n];
return tot;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.