Question

In: Computer Science

I am using NetBeans IDE Java to code and I am seeking comment to the code...

I am using NetBeans IDE Java to code and I am seeking comment to the code as well (for better understanding).

  1. Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, …, n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.

Write a program that reads in 16 values from the keyboard, displays them in a 4 x 4 array, and tests whether they form a magic square.

Example:

              16     3       2      13

               5      10     11     8

               9       6       7      12

               4       15    14     1

You need to test two features:

  1. Does each of the numbers 1, 2, …., 16 occur in the user input?
  2. When the numbers are put into a square, are the sums of the rows, columns, and diagonals equal to each other?

Hint: use a two-dimentional array.

  1. Implement a class Robot that simulates a robot wandering on an infinite plane. The robot is located at a point with integer coordinates and faces north, east, south, or west. Supply methods:

public void turnLeft()

public void turnRight()

public void move()

public Point getLocation()

public String getDirection()

The turnLeft and turnRight methods change the direction but not the location. The move method moves the robot by one unit in the direction it is facing. The getDirection method returns a string "N", "E", "S", or "W".

Solutions

Expert Solution

package Matrix;

import java.util.Scanner;

// Defines class MagicSquareTest
public class MagicSquareTest
{
   // Method to accept data to matrix
   static void accpetData(int matrix[][])
   {
       // Scanner class object created
       Scanner sc = new Scanner(System.in);
      
       // Loops till number of rows
       for(int r = 0; r < matrix.length; r++)
       {
           // Loops till number of columns
           for(int c = 0; c < matrix[r].length; c++)
           {
               // Accepts data for current cell
               System.out.print("\n Enter the data for [" + r + "] [" + c + "]: ");
               matrix[r][c] = sc.nextInt();
           }// End of for loop for column
       }// End of for loop for row
      
       // Loops to display the matrix
       // Loops till number of rows
       for(int r = 0; r < matrix.length; r++)
       {
           // Loops till number of columns
           for(int c = 0; c < matrix[r].length; c++)
           {
               // Accepts data for current cell
               System.out.print(matrix[r][c] + " ");
           }// End of for loop for column
           System.out.println();
       }// End of for loop for row
      
       // Close the scanner
       sc.close();
   }// End of method
  
   // Method to return true if parameter matrix is magic matrix
   // Otherwise returns false
   static boolean checkMagicMatrix(int matrix[][])
   {
       // calculate the sum of the prime diagonal
   int leftDiagonalSum = 0, rightDiagonalSum = 0;
  
   // Loops till end of the matrix to calculate the sum of left diagonal
   for(int r = 0; r < matrix.length; r++)
       leftDiagonalSum = leftDiagonalSum + matrix[r][r];
  
   // Loops till end of the matrix to calculate the sum of right diagonal
   for(int r = 0; r < matrix.length; r++)
       rightDiagonalSum = rightDiagonalSum + matrix[r][matrix.length - 1 - r];
  
   // Checks if left and right diagonal sum is not equal then return false
   if(leftDiagonalSum != rightDiagonalSum)
   return false;
  
   // Loops to calculate each row sum
  
   // Loops till number of rows
   for(int r = 0; r < matrix.length; r++)
   {
       // To store each row sum
   int rowSum = 0;
  
   // Loops till number of columns
   for(int c = 0; c < matrix.length; c++)
   rowSum += matrix[r][c];
  
   // Checks if current row sum is not equals to left diagonal sum
   // then returns false
   if (rowSum != leftDiagonalSum)
   return false;
   }// End of for loop
  
   // Loops to calculate each column sum
  
   // Loops till number of rows
   for(int r = 0; r < matrix.length; r++)
   {
       // To store each column sum
   int colSum = 0;
  
   // Loops till number of columns
   for(int c = 0; c < matrix.length; c++)
   colSum += matrix[c][r];
  
   // Checks if current column sum is not equals to left diagonal sum
   // then returns false
   if(colSum != leftDiagonalSum)
       return false;
   }// End of for loop
   // Otherwise returns true
   return true;
   }// End of method
  
   // main method definition
   public static void main(String []s)
   {
       // Declares a matrix of 4 x 4
       int matrix[][] = new int[4][4];
       // Calls the method to accept and display matrix
       accpetData(matrix);
      
       // Call the method to check matrix is magic matrix or not
       if(checkMagicMatrix(matrix))
           System.out.print("\n Matrix is magic matrix.");
       else
           System.out.print("\n Matrix is not a magic matrix.");
      
   }// End of main method
}// End of class


Sample Output:


Enter the data for [0] [0]: 16

Enter the data for [0] [1]: 3

Enter the data for [0] [2]: 2

Enter the data for [0] [3]: 13

Enter the data for [1] [0]: 5

Enter the data for [1] [1]: 10

Enter the data for [1] [2]: 11

Enter the data for [1] [3]: 8

Enter the data for [2] [0]: 9

Enter the data for [2] [1]: 6

Enter the data for [2] [2]: 7

Enter the data for [2] [3]: 12

Enter the data for [3] [0]: 4

Enter the data for [3] [1]: 15

Enter the data for [3] [2]: 14

Enter the data for [3] [3]: 1
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

Matrix is magic matrix.


Related Solutions

I am using NetBeans IDE Java for coding. I would like the code to be commented...
I am using NetBeans IDE Java for coding. I would like the code to be commented for a better understanding. 1. Implement a class Robot that simulates a robot wandering on an infinite plane. The robot is located at a point with integer coordinates and faces north, east, south, or west. Supply methods: public void turnLeft() public void turnRight() public void move() public Point getLocation() public String getDirection() The turnLeft and turnRight methods change the direction but not the location....
Steps to making your Netbeans IDE (Interactive Development Environment): Download and install Netbeans 8.2 IDE (Java...
Steps to making your Netbeans IDE (Interactive Development Environment): Download and install Netbeans 8.2 IDE (Java SE version only). If you do not have the latest Java installation to match, Netbeans will direct you to download the needed version of Java. If needed, download and install the latest Oracle Official Java Software Development Kit Standard Edition (Java SDK SE), and JUnit. I suggest you do this via the bundle referred to as The Java Development Kit (JDK). Download the architecture...
Java Program using Netbeans IDE Create class Date with the following capabilities: a. Output the date...
Java Program using Netbeans IDE Create class Date with the following capabilities: a. Output the date in multiple formats, such as MM/DD/YYYY June 14, 1992 DDD YYYY b. Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first...
Write this program using an IDE. Comment and style the code according to the CS 200...
Write this program using an IDE. Comment and style the code according to the CS 200 Style Guide. Submit the source code files (.java) below. Make sure your source files are encoded in UTF-8. Some strange compiler errors are due to the text encoding not being correct. Monster collector is a game of chance, where the user tries to collect monsters by guessing the correct numbers between 1 and 5. If the user doesn't guess the incorrect number, you catch...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you finish, your code should access an existing text file that you have created, create an input stream, read the contents of the text file, sort and store the contents of the text file into an ArrayList, then write the sorted contents via an output stream to a separate output text file. Copy and paste the following Java™ code into a JAVA source file in...
Using NetBeans IDE, write a JavaFX application that allows theuser to choose insurance options. Use...
Using NetBeans IDE, write a JavaFX application that allows the user to choose insurance options. Use a ToggleGroup to allow the user to select only one of two insurance types—HMO (health maintenance organization) or PPO (preferred provider organization). Use CheckBoxes for dental insurance and vision insurance options; the user can select one option, both options, or neither option. As the user selects each option, display its name and price in a text field; the HMO costs $200 per month, the...
I am struggling with this java code Objectives: Your program will be graded according to the...
I am struggling with this java code Objectives: Your program will be graded according to the rubric below. Please review each objective before submitting your work so you don’t lose points. 1. Create a new project and class in Eclipse and add the main method. (10 points) 2. Construct a Scanner to read input from the keyboard. (10 points) 3. Use the Scanner to read the name, number of balls, and yards per ball of a yarn type specified by...
I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
IN JAVA: I am using binary and linear search methods in java. How can I Generate...
IN JAVA: I am using binary and linear search methods in java. How can I Generate a new array with 10000 elements, and initialize the elements to random values using Math.random() and how can i sort the array using Arrays.sort(). I just need examples, no exact code is necessary. The array must be of doubles.
Here is my fibonacci code using pthreads. When I run the code, I am asked for...
Here is my fibonacci code using pthreads. When I run the code, I am asked for a number; however, when I enter in a number, I get my error message of "invalid character." ALSO, if I enter "55" as a number, my code automatically terminates to 0. I copied my code below. PLEASE HELP WITH THE ERROR!!! #include #include #include #include #include int shared_data[10000]; void *fibonacci_thread(void* params); void parent(int* numbers); int main() {    int numbers = 0; //user input....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT