Java in netbeans This assignment gives you an opportunity to use arrays to solve
ID: 3673682 • Letter: J
Question
Java in netbeans This assignment gives you an opportunity to use arrays to solve a problem and experiment with the reading and writing of files. For this assignment you are to develop a Java Application for a Magic Squares Game. An n x n matrix is filled with the numbers 1, 2, 3, …, n^2 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. For example, You are to create a Java application, named MagicSquares. The application (a Java program with a main method) allows the user to select the type of algorithm they would like to execute, obtains any required input, computes and outputs the result and allows the user to select again. Your program should display a menu similar to the following and then process the input accordingly: (1) Input magic values from file (2) Construct magic squares from input size and write to file (3) Exit the program Write a method named, inputMagicValues(), that prompts the user for a filename, reads in 2 n values from that file (one number per line) and then tests whether they form a magic square when put into array form. You need to test three features: Did the file contain n^2 numbers for some n ? Does each of the numbers 1, 2, …, n^2 occur exactly once in the input? When the numbers are put into a square (left to right, top to bottom), are all of the sums of the rows, columns, and diagonals equal to each other? (If the size of the input is a square, test whether all of the numbers between 1 and n are present. Then compute the row, column and diagonal sums. The program should print appropriate error messages to the console window when the input is not valid, and print the completed magic square to the console window, similar to that shown above when the input is valid.) Write another method named, constructMagicSquare(), that reads in a value for n from the keyboard, prompts the user for a filename where results should be stored, and then implements the following algorithm to construct magic n x n squares. This algorithm works only if n is odd, so if the use enters an even value for n , you must display an error message and prompt the user for an odd integer. To start the algorithm, place a 1 in the middle of the bottom row. After k has been placed in the [i][j] square, place k + 1 into the square to the right and down, wrapping around the borders. However, if the square to the right and down has already been filled, or if you are in the lower right corner, then you must move to the square straight up instead. Here is the 5x5 square that you get if you follow this method: Your method should write the magic square of order n to the specified file, if n is odd.
Can you help me with this problem? I have some of it done but i am confused on how to do the rest i am using net beans and java can you please help me?
Here is what i have
package magic.squares;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
*
* @author Austin Antoine
*/
public class MagicSquares {
public void inputMagicValue() {
Scanner input = new Scanner(System.in);
Scanner user = new Scanner(System.in);
System.out.println("Enter the type of input for the game:");
System.out.println("Please choose your option 3 is the exit button:");
System.out.println("(1) Input magic values from file:");
System.out.println("(2) Construct magic squares from input size and write to file :");
System.out.println("(3) Exit:");
System.out.println();
//user enter name of their file
System.out.println("Enter input file name ");
String filename = user.nextLine();
java.io.File file = new java.io.File(filename);
int num[]= new int [100];
int i = 0;
int counter = 0; // counter to keep track of # values read
int validate = 0;
int square = 2; // array for input numbers
Scanner inputFile;
for (int j = 0; j < values. );
// read in the numbers from file (i.e inputfile) into a 1-dim array and use a counter(i.e count) to keep track of the number of values that were read
// Chapter 12 - slide 48
while (input.hasNext()) {
values[i]= input.next.Int();
i++;
}
// Check to see if the number of valies read was a perfect square
// Sort the 1-dim array and check to see if every number from 1...count are included in the array
// If the above two checks are valid, then you will need to read in count number of values from the file and
// put them into a 2-dim array.
// Use loops to determine if the sums of the each row, colsand diag contain the same value, if so, print the 2-dim
// array to the console
boolean duplicates = false;
for (int j=0 ; j< single.length;j++)
for ( int k = j+1 ; k< single.length; k++)
if (k!=j)
else {
}
}
//code for user to input magicNumbers here
// the numbers which are going to make up the square and be checked for validity
}
catch (FileNotFoundException ex) {
}
System.out.println("Error - File Not Found");
public void constructMagicSquare() {
Scanner user = new Scanner(System.in);
System.out.println("Enter magicSquare size row and colomn");
int n = user.nextInt();
System.out.println("Enter output file name ");
String outputfile = user.nextLine().trim();
File output = new File(outputfile);
PrintWriter out = new PrintWriter(output);
if (n % 2 == 0) {
System.out.println("size has to be odd");
} else {
int[][] magic = new int[n][n];
int row = n - 1;
int col = n / 2;
magic[row][col] = 1;
for (int i = 2; i <= n * n; i++) {
if (magic[(row + 1) % n][(col + 1) % n] == 0) {
row = (row + 1) % n;
col = (col + 1) % n;
} else {
row = (row - 1 + n) % n;
}
magic[row][col] = i;
}
// create instance of PrintWrite for writing to file....see pages 476-477 of textbook or slide 46 of Chapter 12 notes
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(magic[i][j]);
}
System.out.println();
}
}
out.close();
}
Explanation / Answer
You just need to do some modifications to incorporate your inputvalidation. and input files. here is my code
//-----------------------------------------------------------------------------
// MagicSquare.java
// This program creates an arithmetic sequence based on a starting number and
// the difference between each number in the sequence. It creates a two-dimensional
// array of the arithmetic sequence (matrix) and outputs whether or not the sequence
// created is a magic square.
//-----------------------------------------------------------------------------
import javax.swing.*;
import java.util.*;
import java.io.*;
public class MagicSquare
{
static int[] sequence;
static int[][] matrix;
private static boolean option;
static PrintWriter outFile;
static Scanner inFile;
public static void inputOption()
{
String optionStr;
char optionChar;
optionStr = JOptionPane.showInputDialog("Would you like to input from a file or the command line? Enter f for file, or c for command line.");
optionChar = optionStr.charAt(0);
if (optionChar == 'f' || optionChar == 'F')
{
option = true;
}
else if (optionChar == 'c' || optionChar == 'C')
{
option = false;
}
}
public static void createArithmeticSeq() throws FileNotFoundException
{
String firstStr, diffStr; // Strings necessary for JOptionPane
int first, diff;
String seqStr = "";
first = 0;
diff = 0;
// JOptionPane's for input
if (option == false)
{
firstStr = JOptionPane.showInputDialog("Please enter the first number of the arithmetic sequence.");
first = Integer.parseInt(firstStr); // Parsing out the first number of sequence
diffStr = JOptionPane.showInputDialog("Please enter the difference between each term in the sequence.");
diff = Integer.parseInt(diffStr); // Parsing out the difference between each term
}
else
{
first = inFile.nextInt();
diff = inFile.nextInt();
}
sequence = new int[16];
for (int i=0; i < sequence.length; i++)
{
sequence[i] = first + diff*i;
}
if (option == false)
{
for (int k = 0; k < 16; k++)
{
System.out.printf("%4d", sequence[k]);
/*seqStr = sequence[k]+ "";
JOptionPane.showMessageDialog(null, seqStr, "Arithmetic Sequence",JOptionPane.INFORMATION_MESSAGE); */
}
}
else
{
for (int k = 0; k < 16; k++)
{
outFile.printf("%4d", sequence[k]);
}
}
}// ... End of createArithmeticSeq()
public static void matricize()
{
int row = 0, col;
matrix = new int[4][4];
// Sets two dimensional array row by row. (May be counterintuitive)
for (col = 0; col < matrix[row].length; col++)
{
row = 0;
matrix[row][col] = sequence[col];
}
for (col = 0; col < matrix[row].length; col++)
{
row = 1;
matrix[row][col] = sequence[col + 4];
}
for (col = 0; col < matrix[row].length; col++)
{
row = 2;
matrix[row][col] = sequence[col + 8];
}
for (col = 0; col < matrix[row].length; col++)
{
row = 3;
matrix[row][col] = sequence[col + 12];
}
}// ... End of matricize()
public static void reverseDiagonal()
{
int row, col;
int temp;
for (row = 0; row < matrix.length / 2; row++)
{
temp = matrix[row][row];
matrix[row][row] = matrix[matrix.length - 1 - row][matrix.length - 1 - row];
matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
}
for (row = 0; row < matrix.length / 2; row++)
{
temp = matrix[row][matrix.length - 1 - row];
matrix[row][matrix.length -1 - row] = matrix[matrix.length - 1 - row][row];
matrix[matrix.length - 1 - row][row] = temp;
}
}// ... End of reverseDiagonal()
public static void printMatrix()
{
int row, col;
if (option == false) // Check the user's option for file I/O or command line.
{
// Prints matrix row by row to create a square shaped matrix.
for (col = 0; col < matrix.length; col++)
{
row = 0; // First Row
System.out.printf("%3d", matrix[row][col]);
}
System.out.println("");
for (col = 0; col < matrix.length; col++)
{
row = 1; // Second Row
System.out.printf("%3d", matrix[row][col]);
}
System.out.println("");
for (col = 0; col < matrix.length; col++)
{
row = 2; // Third Row
System.out.printf("%3d", matrix[row][col]);
}
System.out.println("");
for (col = 0; col < matrix.length; col++)
{
row = 3; // Fourth Row
System.out.printf("%3d", matrix[row][col]);
}
}
else
{
// Prints matrix row by row to create a square shaped matrix.
for (col = 0; col < matrix.length; col++)
{
row = 0; // First Row
outFile.printf("%3d", matrix[row][col]);
}
outFile.println("");
for (col = 0; col < matrix.length; col++)
{
row = 1; // Second Row
outFile.printf("%3d", matrix[row][col]);
}
outFile.println("");
for (col = 0; col < matrix.length; col++)
{
row = 2; // Third Row
outFile.printf("%3d", matrix[row][col]);
}
outFile.println("");
for (col = 0; col < matrix.length; col++)
{
row = 3; // Fourth Row
outFile.printf("%3d", matrix[row][col]);
}
}
}// ... End of printMatrix()
public static void magicCheck()
{
int sum = 0, magicNumber, row, col;
int rowSum1 = 0, rowSum2 = 0, rowSum3 = 0, rowSum = 0, colSum1 = 0, colSum2 = 0, colSum3 = 0, colSum = 0, diagSum1 = 0, diagSum = 0;
for (int j = 0; j < sequence.length; j++)
{
sum = sum + sequence[j];
}
magicNumber = sum / 4;
// Sum of Rows
for (col = 0; col < matrix.length; col++)
{
row = 0;
rowSum = rowSum + matrix[row][col];
}
for (col = 0; col < matrix.length; col++)
{
row = 1;
rowSum1 = rowSum1 + matrix[row][col];
}
for (col = 0; col < matrix.length; col++)
{
row = 2;
rowSum2 = rowSum2 + matrix[row][col];
}
for (col = 0; col < matrix.length; col++)
{
row = 0;
rowSum3 = rowSum3 + matrix[row][col];
}
// ...
// Sum of Columns
for (row = 0; row < matrix.length; row++)
{
col = 0;
colSum = colSum + matrix[row][col];
}
for (row = 0; row < matrix.length; row++)
{
col = 1;
colSum1 = colSum1 + matrix[row][col];
}
for (row = 0; row < matrix.length; row++)
{
col = 2;
colSum2 = colSum2 + matrix[row][col];
}
for (row = 0; row < matrix.length; row++)
{
col = 3;
colSum3 = colSum3 + matrix[row][col];
}
// ...
// Sum of Diagonals
for (row = 0,col = 0; row < matrix.length && col < matrix.length; row++)
{
diagSum = diagSum + matrix[row][col];
col = col++;
}
for (col = 0, row = 3; col < matrix.length && row < matrix.length; col++)
{
diagSum1 = diagSum1 + matrix[row][col];
row--;
}
//...
// Begin of magic check
if (rowSum == magicNumber && rowSum1 == magicNumber && rowSum2 == magicNumber && rowSum3 == magicNumber &&
colSum == magicNumber && colSum1 == magicNumber && colSum2 == magicNumber && colSum3 == magicNumber &&
diagSum == magicNumber && diagSum1 == magicNumber)
{
if (option == false)
{
System.out.println("It is a magic square.");
}
else
{
outFile.println("It is a magic square.");
}
}
else
{
if (option == false)
{
System.out.println("It is not a magic square.");
}
else
{
outFile.println("It is not a magic square.");
}
}
}
public static void main(String[] args) throws FileNotFoundException
{
try {
outFile = new PrintWriter("c:\magicsquare.txt");
inFile = new Scanner(new FileReader("c:\sequence.txt"));
inputOption();
//Array methods don't require parameters, arrays can be changed anywhere within the program.
createArithmeticSeq();
System.out.println("");
outFile.println("");
System.out.println("");
outFile.println("");
matricize();
printMatrix();
System.out.println("");
outFile.println("");
System.out.println("");
outFile.println("");
reverseDiagonal();
printMatrix();
System.out.println("");
outFile.println("");
System.out.println("");
outFile.println("");
magicCheck();
inFile.close();
outFile.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File not found!", "Error", JOptionPane.WARNING_MESSAGE);
}
}// ... End of main()
}// ... End of class MagicSquare
//////////////////////// sequence.txt ////////////////
21
5
/////////////////////// magicsquare.txt //////////////////////////
21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
21 26 31 36
41 46 51 56
61 66 71 76
81 86 91 96
96 26 31 81
41 71 66 56
61 51 46 76
36 86 91 21
It is a magic square.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.