Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need some help starting off this Java program dealing with Magic Squares. I need

ID: 3811892 • Letter: N

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 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

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();
}
}
}

4 9 2 3 5 7 8 1 6

Explanation / Answer

Hi

I have modified the code and highlighted the code changes below

MagicSquare.java


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: " );//square.txt
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];
  
for ( int r = 0; r < square.length; r++ ) {
for ( int c = 0; c < square.length; c++ ) {
square[r][c] = input.nextInt();
}
   }
System.out.println("Array elements are: ");
for ( int r = 0; r < square.length; r++ ) {
for ( int c = 0; c < square.length; c++ ) {
System.out.print(square[r][c]+" ");
}
System.out.println();
}


}
catch ( Exception ex ) {
System.out.println ( "An error has occurred!" );
ex.printStackTrace();
}
}
}

Output:


Enter input filename:
D:\square.txt
Array elements are:
4 9 2
3 5 7
8 1 6

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote