Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change an ArrayList into a 2D array in Java

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));
            }
         }
      }
}
like image 210
Caitlyn Daly Avatar asked Apr 05 '26 19:04

Caitlyn Daly


1 Answers

I see two cases:

  1. User gives the size at the beginning
  2. User doesn't.

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.

like image 123
xenteros Avatar answered Apr 08 '26 09:04

xenteros