Reputation: 45
I am supposed to be making a program that tests a user inputed matrix is a magic square. Basically I should be putting user input into an ArrayList which is then placed into a 2D array that can then be used to calculate the sum of the rows, col, and diagonals to see if they have the same sum. This is what I have so far. I cant get the ArrayList to make a 2D array.
import java.util.*;
class Square
{
private int[][] square;
private ArrayList<Integer> numbers;
public int numInput;
public Square()
{
numbers = new ArrayList<Integer>();
int[][] square;
numInput = 0;
}
public void add(int i)
{
numbers.add(i);
}
}
public boolean isSquare()
{
numInput = numbers.size();
double squared = Math.sqrt(numInput);
if (squared != (int)squared)
{
System.out.println("Numbers make a square");
return true;
}
else
{
System.out.println("Numbers do not make a square");
return false;
}
}
public String isMagicSquare()
{
for (int row=0; row<numInput; row++)
{
for (int col=0; col<numInput; col++)
{
square[row][col] = number.get(col +( number.size() * row));
}
}
}
}
Upvotes: 3
Views: 742
Reputation: 12817
There is a typo in identifying the perfect square
it should be
if (squared == (int) squared) return true;
You can initialize and fill 2D array if its a perfect square
public String isMagicSquare() {
if (isSquare()) {
int size = (int) Math.sqrt(numbers.size());
this.square = new int[size][size];
for (int i = 0; i < numbers.size(); i++) {
square[i / size][i % size] = numbers.get(i);
}
return Arrays.deepToString(square); // do other op on the array and return appropriate String
} else {
return null;
}
}
Upvotes: 0
Reputation: 15842
I see two cases:
Ad. 1.
No need to use an ArrayList
. Simply read the input this way:
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = s.nextInt();
}
}
Ad. 2.
I simply scan numbers as long, as user gives numbers. Then check if he gave proper amount of numbers. Then convert to a square array of ints.
ArrayList<Integer> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
list.add(s.nextInt());
}
int n = list.size();
double sqrt = Math.sqrt(n);
int x = (int) sqrt;
if(Math.pow(sqrt,2) != Math.pow(x,2)) {
//wrong input - it wasn't a square
}
int[][] array = new int[x][x];
int index = 0;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
array[i][j] = array.get(index++);
}
}
Obviously you need to take care about error handling. If you have further questions, ask in comments. I'll update my answer if you're interested.
Upvotes: 2