In: Computer Science
Write a program to prompt the user to display the following menu:
Sort Matrix Quit
How many numbers: 6
Original numbers: Sorted numbers
34 2
55 11
2 34
89 55
78 78
11 89
Do you want to quit? Q
Do you want to quit? Q
If the user enters ‘Q’ or ‘’, your program should terminate the program.
import java.util.Scanner;
public class SortMatrix
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);//create object of
scanner class
char ch;
while(true)
{
System.out.println("********Menu********");
System.out.println("Sort (Press 'S'
or 's')");
System.out.println("Matrix (Press
'M' or 'm')");
System.out.println("Quit (Press
'Q')");
System.out.print("Enter Choice =
");
ch = sc.next().charAt(0);/// get
menu choice from user
//use switch case
switch(ch)
{
case 'S': // user enter choice in
both cases small letter or capital letter
case 's':
int num,temp=0;
System.out.print("How many numbers
you wish to read = ");
num = sc.nextInt(); //stored size
of array
//create two array
int arr[] = new int[num];
int arr2[] = new int[num];
System.out.println("Enter numbers
in array = ");
for(int
i=0;i<arr2.length;i++)
{
arr2[i] = sc.nextInt();//insert
element in array
}
for(int
i=0;i<arr2.length;i++)
{
arr[i] = arr2[i]; //copy arr2 in
arr for print original array
}
//sort array
for(int
i=0;i<arr2.length;i++)
{
for(int
j=i+1;j<arr2.length;j++)
{
if(arr2[i]>arr2[j])
{
temp = arr2[i];
arr2[i] = arr2[j];
arr2[j] = temp;
}
}
}
//print array in proper
format
System.out.println("Original
Numbers\tSorted Numbers");
for(int
i=0;i<arr2.length;i++)
{
System.out.println("\t"+arr[i]+"\t\t\t"+arr2[i]);
}
break;
case 'M': // user enter choice in
both cases small letter or capital letter
case 'm':
//create three 2D array
int matA[][] = new int[2][2];
int trasA[][] = new
int[2][2];
int matC[][] = new int[2][2];
System.out.println("Enter number in
2*2 matrix = ");
for(int
i=0;i<matA.length;i++)
{
for(int
j=0;j<matA.length;j++)
{
matA[i][j] = sc.nextInt();//insert
element in array first
}
}
// transpose matrix
for(int
i=0;i<matA.length;i++)
{
for(int
j=0;j<matA.length;j++)
{
trasA[i][j] = matA[j][i];
}
}
//addition of Original matrix and
transpose matrix stored in matc
for(int
i=0;i<matA.length;i++)
{
for(int
j=0;j<matA.length;j++)
{
matC[i][j] = matA[i][j] +
trasA[i][j];
}
}
//print all three matrix
System.out.println("Original
Matrix\t\tTraspose Matrix\t\tAddition Matrix");
for(int
i=0;i<matA.length;i++)
{
for(int
j=0;j<matA.length;j++)
{
System.out.print("
"+matA[i][j]+"\t");
}
System.out.print("\t");
for(int
j=0;j<trasA.length;j++)
{
System.out.print("
"+trasA[i][j]+"\t");
}
System.out.print("\t");
for(int
j=0;j<matC.length;j++)
{
System.out.print("
"+matC[i][j]+"\t");
}
System.out.print("\t");
System.out.println("");
}
break;
case 'Q':
//exit in while loop
System.exit(0);
break;
default:
System.out.println("Invalis Choice");
break;
}
}
}
}
==================================OUTPUT===============================
==Please Upvote==