A magic square is an n-by-n grid of integers with the property
when added up sum to the same constant. For instance, for this simple magic square the constant is (obviously) 15.
| 8 | 1 | 6 |
| 3 | 5 | 7 |
| 4 | 9 | 2 |
A normal magic square has the additional property that it contains all the integers from 1 to n squared. Thus
| 1 | 1 |
| 1 | 1 |
is a “non-normal“ magic square.
Implement and test a class that determines whether or not
a square is “magic.”
The method testAllCandidates( String filename )
shall open the specified file, each line of which contains
the int values that comprise a single candidate. For each candidate,
print the square (columns separated by TABS) and on the final
row (one TAB after the last column) either
followed by 2 newline characters. For example, the input file:
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 1 1 1 1 1 2 3 4 |
would result in this output:
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 is magic (34) 1 1 1 1 is non-normal but magic (2) 1 2 3 4 is not a magic square |
6 32 3 34 35 1 7 11 27 28 8 30 19 14 16 15 23 24 18 20 22 21 17 13 25 29 10 9 26 12 36 5 33 4 2 31 4 14 15 1 9 7 6 12 5 11 10 8 16 2 3 13 22 47 16 41 10 35 4 5 23 48 17 42 11 29 30 6 24 49 18 36 12 13 31 7 25 43 19 37 38 14 32 1 26 44 20 21 39 8 33 2 27 45 46 15 40 9 34 3 28 37 78 29 70 21 62 13 54 5 6 38 79 30 71 22 63 14 46 47 7 39 80 31 72 23 55 15 16 48 8 40 81 32 64 24 56 57 17 49 9 41 73 33 65 25 26 58 18 50 1 42 74 34 66 67 27 59 10 51 2 43 75 35 36 68 19 60 11 52 3 44 76 77 28 69 20 61 12 53 4 45
new Scanner( aStringReference ) does? That's right... it scans for tokens within that String!
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.File;
import java.util.HashMap;
public class PracticeLab
{
private ArrayList data; // hints: get/add/size
private HashMap map; // hints: get/put/containsKey
// extract an int from a String (e.g., "123" would return 123)
public int stringToInt( String s )
{
return Integer.parseInt( s );
}
// demonstrates how to get a String from the user
public void demo()
{
String name = JOptionPane.showInputDialog( "What is your name?" );
System.out.println( "Hi, " + name + "! Pleased to meet you!" );
}
public void tryThis()
{
System.out.println( "What\tdoes\tthis\n\tprint?" );
}
public void printFile( String filename )
{
Scanner scan = null; // hints: hasNext/next/hasNextLine/nextLine
try
{
scan = new Scanner( new File( filename ) );
}
catch ( java.io.FileNotFoundException e )
{
System.out.println( "Couldn't open " + filename );
System.exit( -1 ); // terminate the program
}
while ( scan.hasNextLine() )
{
System.out.println( scan.nextLine() );
}
}
}
Remember: the quizzes are closed book, closed notes, and closed internet. You may use only those files that are provided as part of the quiz (if any) and files that you write during that quiz period.