In: Computer Science
Write the following program in Java.
Ask the user to enter the number of rows and columns for a 2-D
array. Create the
array and fill it with random integers using (int)(Math.random() *
20) (or whatever
number you choose). Then, provide the user with several menu
choices.
1. See the entire array.
2. See a specific row.
3. See a specific column.
4. See a specific value.
5. Calculate the average of each row.
6. Calculate the total of each column.
7. Exit
If the user chooses option:
1 - output the entire array in chart format.
2 - ask the user for the specific row number and output the values
from that row,
all columns, going across the screen.
3 - ask the user for the specific column number and output the
values from that
column, all rows, going down the screen.
4 - ask the user for the specific row and column number and output
the value at
that position (1 value only).
5 - output the information in chart format, including placing the
average at the
end of each row.
6 - output the information in chart format, including placing the
total below each
column.
7 - thank the user and exit the program
Any other option should produce an error message.
The program should continue until the user chooses option 7.
Please try to use basic coding(nothing too complicated so I can understand)
/* Below is your required code,please upvote for the efforts*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int rows,cols;
System.out.println("Enter rows and columns");
rows=sc.nextInt();
cols=sc.nextInt();
int a[][]=new int[rows][cols];
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
a[i][j]=(int)(Math.random() * 20);
while(true){
System.out.println("\n1. See the entire array. \n2.
See a specific row.\n3. See a specific column.\n4. See a specific
value.\n5. Calculate the average of each row.\n6. Calculate the
total of each column.\n7. Exit\n");
int choice=sc.nextInt();
if(choice==1){
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}
else if(choice==2){
System.out.println("\nEnter Row = ");
int r=sc.nextInt();
for(int j=0;j<cols;j++)
System.out.print(a[r-1][j]+" ");
}
else if(choice==3){
System.out.println("\nEnter Column = ");
int c=sc.nextInt();
for(int j=0;j<rows;j++)
System.out.println(a[j][c-1]);
}
else if(choice==4){
System.out.println("\nEnter Row and Column = ");
int r=sc.nextInt();
int c=sc.nextInt();
System.out.println("\n"+a[r-1][c-1]);
}
else if(choice==5){
float avg=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(a[i][j]+" ");
avg+=a[i][j];
}
System.out.print(avg/cols+"\n");
}
}
else if(choice==6){
float[] avg=new float[cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(a[i][j]+" ");
avg[j]+=a[i][j];
}
System.out.println();
}
for(int j=0;j<cols;j++)
System.out.print(avg[j]+" ");
}
else if(choice==7)
System.exit(0);
}
}
}