Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need help with my code. Overview of Magic Squares A magic square is an arrangement numbers from 1 to N2 in an NxN matrix,

I need help with my code.

Overview of Magic Squares

A magic square is an arrangement numbers from 1 to N2 in an NxN matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal must be N(N2+1)/2.

Here is an example 4x4 magic square. Notice that all of the rows add up to 34 [which is (4*(42+1))/2], all of the columns add up to 34, and both of the main diagonals add up to 34. Also notice that each of the numbers from 1 through 16 is used only once each in the square and that only the numbers 1 through 16 are used:

 1 2 15 16 13 14 3 4 12 7 10 5 

8 11 6 9

Overview of Assignment

You will be reading in the contents of a file that contain a potential magic square and then analyzing it to determine if it's a magic square or not. Information about reading from files is discussed later in the assignment.

The file that you read from will look something like this:

4 1 2 15 16 1314 3 4 12 7 10 5 8 11 6 9

The first line of the file is the number of rows and columns in a potential magic square. This number will be at least 3 but could potentially be any number larger than 3 . The files that we test will only contain reasonably-sized matrices, up to about 15 or 20. The remaining integers in the file will fill up an NxN matrix that represents a potential magic square.

Your program will prompt the user to enter a filename to read from, will read the file and store the square into a 2-d array of integers and then check the following conditions, reporting any errors that may be present:

First, the program will check each row to determine if it satisfies the conditions of that particular magic square (i.e., does each row add up to the magic number for that potential square?). Output either GOOD or BAD for each row (numbered from 1 through N). Label each row's output with ROW #: , where # is the row number starting at 1.

Second, the program will check each column to determine if it satisifies the conditions of that particular magic square (i.e., does each column add up to the magic number for that potential square?). Output either GOOD or BAD for each row (numbered from 1 through N). Label each row's output with

COL #: , where # is the col number starting at 1. Third, your program will check each of the main diagonals (from top-left to bottom-right, known as "diagonal 1" and then from bottom-left to top-right, known as "diagonal 2"). Output either GOOD or

BAD for each row (numbered 1 or 2 as appropriate). Label each diagonals's output with DIAG #: , where # is the diagonal number starting at 1. Fourth, your program should check to see if each value in the square has been used exactly once. If all values in the appropriate range have been used exactly once, output GOOD . Otherwise, if a value has been used more than once or has not been used at all, output a list of those values in ascending order with a space between each value. Label this output with UNIQUE: .

Lastly, your program needs to identify the square as either magic or not by outputting GOOD or BAD for a final MAGIC SQUARE: label.

Reading input from a file instead of the keyboard

In order to process a file for input instead of keyboard input, you'll need to be able to open and read from a text file in Java. There are a number of different ways to do this, and you'll explore more involved ways to process files if you take more programming courses, but for what we need this semester we'll create a Scanner that is attached to a file so that input will basically behave the same way that you've been processing things all semester, just from a file instead of the keyboard.

It is important and imperative that you work with this code until you are certain you have a good handle on how it's setting up an external file for reading before moving on to the next part of the assignment.

The methods to write for this program

Here are the five additional methods you need to write in addition to your main() method for this program. They are described using javadoc notation.

Method display()

/** * display() * * This method displays the square in nice, tidy rows and columns. * Each row should be labeled as [XX], where XX is the number of the * row, and each column should have an [XX] above it as a header * where XX is the column number. * * The method should also display a textual header about the size of * the square and the magic number of the square. See the example runs * for an idea what the output should look like. * * @param * @param * @return */ 
square a 2-d int array representing the square magicnum an int containing the calculated magic number None 

Java

Method rowCheck()

 /** * rowCheck() * * This method checks each row to see if it is a valid row, with all * values adding up to the magic number sent in as an argument. Label * the row outputs starting at 1. * * The output should be either the text GOOD or BAD, depending on the * status of the individual row. If the row is BAD, also include what * that row added up to instead of the magic number. See the example * runs for an idea what the output should look like. * * The method should return true if all of the rows are valid and false * otherwise. * * @param * @param * @return */ 

Java

square magicnum boolean 
a 2-d int array representing the square an int containing the calculated magic number true or false if all of the rows are valid 

Method colCheck()

 /** * colCheck() * * This method checks each column to see if it is a valid column, with all * values adding up to the magic number sent in as an argument. Label * the column outputs starting at 1. * * The output should be either the text GOOD or BAD, depending on the * status of the individual column. If the column is BAD, also include what * that column added up to instead of the magic number. See the example * runs for an idea what the output should look like. * * The method should return true if all of the columns are valid and false * otherwise. * * @param * @param * @return */ 

Java

square magicnum boolean 
a 2-d int array representing the square an int containing the calculated magic number true or false if all of the columns are valid 

Method diagCheck()

 /** * diagCheck() * * This method checks the two major diagonals to see if they are valid, * with all values adding up to the magic number sent in as an argument. * Label the diagonal from upper-left corner (position [0][0]) to the * bottom-right corner (position [n-1][n-1]) as DIAG 1. Label the * other diagonal as DIAG 2. * * The output should be either the text GOOD or BAD, depending on the * status of the individual diagonal. If the diagonal is BAD, also include * what that diagonal added up to instead of the magic number. See the * example runs for an idea what the output should look like. * * The method should return true if both of the diagonals are valid and false * otherwise. * * @param * @param * @return */ 

Java

square magicnum boolean 
a 2-d int array representing the square an int containing the calculated magic number true or false if both of the diagonals are valid 

Method uniqueCheck()

 /** * uniqueCheck() * * This method checks to see if each value used in the potential magic * square has been used once and only once in the entirety of the square. * * Different-sized squares will have different potential ranges of values * to test. For instance, a 4x4 square will have 16 potential values * to test (1-16). A 7x7 square will have 49 potential values to test. * * If all values in the appropriate range have been used only once, * the output should be the text GOOD for the label UNIQUE. * * If a value was used more than once or wasn't used at all, it should * be listed in order from smallest to largest with a space between each * offending value. * * See the example runs for an idea what the output should look like. * * The method should return true if all values have been used exactly once * and false otherwise. * * @param square a 2-d int array representing the square * @return boolean true or false if all values are used exactly once */ 

Java

Goals

Read a text file and store the data into a 2-d array for processing. Utilize a 2-dimensional array to store your square. Possibly utilize a 1-dimensional array to help with determining uniqueness of values in the square. Work extensively with arrays and passing arrays to methods for processing.

Points to Think About

If your code is structured well, it should be able to adapt to an any-sized NxN array, meaning you don't need to (and shouldn't) write special cases for 3x3, 4x4, 5x5, etc. arrays. Think about if someone wanted to test a 100x100 square, a 56x56 square or a 974x974 square. Can you easily write code for every possible size of square?

Processing the 2-d array for displaying and for checking the rows will follow the structure of many of the 2- d array examples seen in class. Processing the 2-d array so you are adding up columns is not as straightforward and isn't simply a straight variation on the row processing you may have done for the rowCheck() method.

Checking the [0][0] to [n-1][n-1] diagonal is pretty straightforward. Checking the [0][n-1] to [n-1][0] diagonal can also be straightforward if structured correctly.

Developing Your Program

As you know by now, when developing a complex program, it's best to do it in stages. For this program, you might try using these guidelines as milestones to reach:

Set up the code to prompt for a filename, open the file and process it into an appropriately-sized 2-d array of integers. If the file specifies that the array is of size 6, create a 6x6 int array. If the file specifies that the array is of size 9, create an 9x9 int array and then fill it.

To ensure that you are reading the file properly and filling the array correctly, write the display() method first and use it to display your square. Make sure to label the rows and columns in the output appropriately.

The next method to write should be the rowCheck() method, as processing the array to check the rows will be very similar to processing 2-d arrays as you've seen in examples in class. You just need to

add in some additional conditional checking and output. In addition to generating the correct output, make

sure you set the method up to return true or false if all of the rows are good or not.

After this, write the colCheck() method, which will be similar to the rowCheck() method.

Next, write the diagCheck() method.

Then, write the uniqueCheck() method. This will likely be the trickiest to write. How will you keep

track of which numbers have been used and which numbers haven't when there are varying numbers of

values depending on the size of the square?

Finally, use the boolean results from rowCheck() , colCheck() , diagCheck() and

uniqueCheck() to do a final output of GOOD or BAD regarding the square's "magic square" property.

My code

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

// Get the name of the input file

System.out.printf("Enter input filename: ");

String inputName = keyboard.nextLine();

int[][] grid;

try

{

// Create a file stream with the user's input file

File inputFile = new File(inputName);

// Use that file and connect it to Scanner

Scanner input = new Scanner(inputFile);

//Reading in the size of the square

int size = input.nextInt();

int magicnum = size*((int)Math.pow(size,2)+1)/2;

grid = new int [size][size];

//reading in values in the ssquare

for (int i = 0; i < grid.length; i++) {

for(int j = 0; j < grid[i].length; j++) {

grid[i][j] = input.nextInt();

}

}

//Prints the size of the grid

System.out.printf("Checking a %dx%d square! ", size, size);

displaySquare(grid, magicnum);

// Check each aspect of the grid so if all of these things are valid then it is a magic square!!

boolean rowsValid = checkRows(grid,magicnum);

boolean colsValid = checkColumns(grid,magicnum);

boolean diagValid = checkDiagonals(grid,magicnum);

boolean uniqValid = checkUnique(grid);

if (rowsValid && colsValid && diagValid && uniqValid)

{

System.out.println("MAGIC SQUARE: GOOD");

}

else

{

System.out.println("MAGIC SQUARE: BAD");

}

}

//try catch, same as used in ppm assignment

catch (Exception e)

{

System.out.println(e);

}

}

/**

* displaySquare()

*

* This method displays the square in nice, tidy rows and columns.

* Each row should be labeled as [XX], where XX is the number of the

* row, and each column should have an [XX] above it as a header

* where XX is the column number.

*

* The method should also display a textual header about the size of

* the square and the magic number of the square. See the example runs

* for an idea what the output should look like.

*

* @param square a 2-d int array representing the square

* @param magicnum an int containing the calculated magic number

* @return None

*/

public static void displaySquare(int[][] square, int magicnum) {

System.out.printf("The magic number is %d. ", magicnum);

// Print the header

System.out.printf(" ");

for (int i = 0; i < square.length; i++)

{

System.out.printf("[%2d] ", i+1);

}

System.out.println();

// Print each row

for (int row = 0; row < square.length; row++) {

// On a new row, print the row number

System.out.printf("[%2d] ", row+1);

for(int col = 0; col < square[row].length; col++) {

System.out.printf("%4d ", square[row][col]);

}

System.out.println();

}

}

/**

* checkRows()

*

* This method checks each row to see if it is a valid row, with all

* values adding up to the magic number sent in as an argument. Label

* the row outputs starting at 1.

*

* The output should be either the text GOOD or BAD, depending on the

* status of the individual row. If the row is BAD, also include what

* that row added up to instead of the magic number. See the example

* runs for an idea what the output should look like.

*

* The method should return true if all of the rows are valid and false

* otherwise.

*

* @param square a 2-d int array representing the square

* @param magicnum an int containing the calculated magic number

* @return boolean true or false if all of the rows are valid

*/

public static boolean checkRows(int[][] square, int magicnum) {

int total = 0;

boolean valid = true;

//moves through the grid row by row

for (int row = 0; row < square.length; row++) {

//sets total back to zero so youre not adding each row together, only the numbers in one row

total = 0;

// this moves through the rows and adds them together

for(int col = 0; col < square[row].length; col++) {

total += square[row][col];

}

if (total == magicnum) {

System.out.printf("ROW %d: GOOD ", row+1);

}

else {

System.out.printf("ROW %d: BAD (%d instead of %d) ", row+1, total, magicnum);

valid = false;

}

}

return valid;

}

/**

* checkColumns()

*

* This method checks each column to see if it is a valid column, with all

* values adding up to the magic number sent in as an argument. Label

* the column outputs starting at 1.

*

* The output should be either the text GOOD or BAD, depending on the

* status of the individual column. If the column is BAD, also include what

* that column added up to instead of the magic number. See the example

* runs for an idea what the output should look like.

*

*

* The method should return true if all of the columns are valid and false

* otherwise.

*

* @param square a 2-d int array representing the square

* @param magicnum an int containing the calculated magic number

* @return boolean true or false if all of the columns are valid

*/

public static boolean checkColumns(int[][] square, int magicnum) {

int total = 0;

boolean valid = true;

for (int col = 0; col < square.length; col++) {

//sets total back to zero so you are only adding up the values in one col

total = 0;

//moves through the numbers in a col by moving down the rows

for(int row = 0; row < square[col].length; row++) {

total += square[row][col];

}

if (total == magicnum) {

System.out.printf("COL %d: GOOD ", col+1);

}

else {

System.out.printf("COL %d: BAD (%d instead of %d) ", col+1, total, magicnum);

valid = false;

}

}

return valid;

}

/**

/**

* checkDiagonals()

*

* This method checks the two major diagonals to see if they are valid,

* with all values adding up to the magic number sent in as an argument.

* Label the diagonal from upper-left corner (position [0][0]) to the

* bottom-right corner (position [n-1][n-1]) as DIAG 1. Label the

* other diagonal as DIAG 2.

*

* The output should be either the text GOOD or BAD, depending on the

* status of the individual diagonal. If the diagonal is BAD, also include

* what that diagonal added up to instead of the magic number. See the

* example runs for an idea what the output should look like.

*

* The method should return true if both of the diagonals are valid and false

* otherwise.

*

* @param square a 2-d int array representing the square

* @param magicnum an int containing the calculated magic number

* @return boolean true or false if both of the diagonals are valid

*/

public static boolean checkDiagonals(int[][] square, int magicnum){

int total =0;

boolean valid = true;

//Checks the diag from top left to bottom right!! because it starts at 0,0

for(int i = 0; i < square.length; i++){

total += square[i][i];

}

if (total == magicnum) {

System.out.printf("DIAG 1: GOOD ");

}

else {

{

System.out.printf("DIAG 1: BAD ");

valid = false;

}

// checks the diag from top right to bottom left because it start at first row last col

int col = square.length - 1;

total = 0;

for(int row = 0; row < square.length; row++){

total += square[row][col];

col--;

}

if (total == magicnum) {

System.out.printf("DIAG 2: GOOD ");

}

else {

System.out.printf("DIAG 2: BAD ");

valid = false;

}

return valid;

}

/**

* checkUnique()

*

* This method checks to see if each value used in the potential magic

* square has been used once and only once in the entirety of the square.

*

* Different-sized squares will have different potential ranges of values

* to test. For instance, a 4x4 square will have 16 potential values

* to test (1-16). A 7x7 square will have 49 potential values to test.

*

* If all values in the appropriate range have been used only once,

* the output should be the text GOOD for the label UNIQUE.

*

* If a value was used more than once or wasn't used at all, it should

* be listed in order from smallest to largest with a space between each

* offending value.

*

* See the example runs for an idea what the output should look like.

*

* The method should return true if all values have been used exactly once * and false otherwise.

*

* @param square a 2-d int array representing the square

* @return boolean true or false if all values are used exactly once

*/

public static boolean checkUnique( int [][] square){

int[] freq = new int [square.length*square.length];

boolean valid = true;

for (int row = 0; row < square.length; row++) {

for(int col = 0; col < square[row].length; col++) {

// is this number in the range of 1 to n^2?

if (square[row][col] < 1 || square[row][col] > square.length*square.length)

{

System.out.printf("%d is out of range of [1,%d] ",

square[row][col], square.length*square.length);

valid = false;

}

else

{

freq[square[row][col]-1] += 1;

}

// If the number at this coordinate has already been found

if (freq[square[row][col]-1] > 1)

{

System.out.printf("%d is a duplicate value. ", square[row][col]);

valid = false;

}

else

{

freq[square[row][col]-1] += 1;

}

// If the number at this coordinate has already been found

if (freq[square[row][col]-1] > 1)

{

System.out.printf("%d is a duplicate value. ", square[row][col]);

valid = false;

}

}

}

if (valid)

{

System.out.printf("UNIQUE: GOOD ");

}

else {

System.out.printf("UNIQUE: ");

for (int i = 0; i < freq.length; i++)

{

if (freq[i] > 1 || freq[i] == 0)

{

System.out.printf("%d ", i+1);

}

}

System.out.println();

}

return valid;

}

}

the errors im getting:

magic.java:407: error: illegal start of expression public static boolean uniqueCheck( int [][] square){ ^ magic.java:407: error: illegal start of expression public static boolean uniqueCheck( int [][] square){ ^ magic.java:407: error: ';' expected public static boolean uniqueCheck( int [][] square){ ^ magic.java:407: error: '.class' expected public static boolean uniqueCheck( int [][] square){ ^ magic.java:407: error: ';' expected public static boolean uniqueCheck( int [][] square){ ^ magic.java:517: error: reached end of file while parsing } ^ 6 errors 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Analytics Systems Engineering Cybersecurity Project Management

Authors: Christopher Greco

1st Edition

168392648X, 978-1683926481

More Books

Students also viewed these Databases questions

Question

8. Explain the difference between translation and interpretation.

Answered: 1 week ago

Question

10. Discuss the complexities of language policies.

Answered: 1 week ago

Question

1. Understand how verbal and nonverbal communication differ.

Answered: 1 week ago