Question: Need some help starting off this Java program dealing with Magic Squares. I need to modify this code somehow so that it will read in
Need some help starting off this Java program dealing with Magic Squares. I need to modify this code somehow so that it will read in an appropriately sized 2-d array of integers. So, if the file specifies that the array is of size 6, create a 6x6 array. The first integer in the file specifies the number of the rows and the number of the columns. As an example, say the first file looks like this:
3
| 4 | 9 | 2 |
| 3 | 5 | 7 |
| 8 | 1 | 6 |
import java.util.Scanner; import java.io.File;
public class MagicSquare { private static Scanner input = new Scanner ( System.in ); public static void main ( String args [] ) { try { Scanner keyboard = new Scanner ( System.in ); System.out.println ( " Enter input filename: " ); String inFile; inFile = keyboard.next();
File file = new File ( inFile ); Scanner input = new Scanner ( file );
int first = input.nextInt(); final int ROWS = first; final int COLS = first; int[][] square = new int[ROWS][COLS]; while ( input.hasNext() ) { int v = input.nextInt(); for ( int r = 0; r < square.length; r++ ) { square[r][c] = v; for ( int c = 0; c < square.length; c++ ) square[r][c] = v; } } System.out.println ( first );
} catch ( Exception ex ) { System.out.println ( "An error has occurred!" ); ex.printStackTrace(); } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
