Write a Java application that takes a set of n2 numbers from

Write a Java application that takes a set of n^2 numbers from standard input (keyboard) for some n not known in advance, and composes a 2-dim array from them. For example, if the input numbers were 2 45 16 22 17 21 67 29 45 67 97 35 68 34 90 72 they have to be arranged in a 2-dim array as follows: Your program has to check if the number of input numbers is a square of an integer and report an error and terminate if this is not the case. You can assume that at most 100 numbers will be entered. If the input numbers can be arranged in an nxn table, the program has to iprint out the resulting table and compute the sum of numbers on each of the diagonals and print them out. For the above example the following sums have to be computed: diag1 =2 + 21 + 97 + 72 diag2 = 22 + 67 + 67 + 68 Your program should work for any set of numbers, not just for the one above. Name the project Hw5_3

Solution

// DiagonalSum.java
import java.util.Scanner;
class DiagonalSum
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);

    System.out.println(\"Enter set of numbers: \");
    String input = sc.nextLine();
  
    String[] numbers = input.split(\" \");

    int size = numbers.length;

    // check if number of input numbers is a perfect square
    double sqrt = Math.sqrt(size);
   int sqrtSize = (int) sqrt;
   if(Math.pow(sqrt,2) != Math.pow(sqrtSize,2))
   {
       System.out.println(\"2-Dim array cannot be formed from input numbers\");
       System.exit(1);
   }

   int[] numberarray = new int[size];
   for (int i = 0; i < size ; i++ )
   {  
       numberarray[i] = Integer.parseInt(numbers[i]);
   }

   int k = 0;
   int[][] matrix = new int[sqrtSize][sqrtSize];
   for (int i = 0; i < sqrtSize ; i++ )
   {  
       for (int j = 0; j < sqrtSize ; j++ )
       {  
           matrix[i][j] = numberarray[k];
           k++;
       }
   }
  
int diagonal1 = 0;
int diagonal2 = 0;
for (int i = 0; i < sqrtSize ; i++ )
   {  
       diagonal1 = diagonal1 + matrix[i][i];
       diagonal2 = diagonal2 + matrix[i][sqrtSize-i-1];
   }
   
    System.out.println(\"Diagonal1 Sum: \" + diagonal1);
    System.out.println(\"Diagonal2 Sum: \" + diagonal2);

}
}

/*
output;

Enter set of numbers:
1 2 3 4 5 6 7 8
2-Dim array cannot be formed from input numbers


Enter set of numbers:
2 45 16 22 17 21 67 29 45 67 97 35 68 34 90 72
Diagonal1 Sum: 192
Diagonal2 Sum: 224

*/

 Write a Java application that takes a set of n^2 numbers from standard input (keyboard) for some n not known in advance, and composes a 2-dim array from them.
 Write a Java application that takes a set of n^2 numbers from standard input (keyboard) for some n not known in advance, and composes a 2-dim array from them.

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site