如何在Java中将一个ArrayList转换成一个二维数组

3

我应该制作一个程序,测试用户输入的矩阵是否为幻方。基本上,我应该将用户输入放入ArrayList中,然后放入2D数组中,以便计算行、列和对角线的总和,看它们是否具有相同的总和。这是我目前的代码。但我无法将ArrayList转换成2D数组。

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

1
int[][] square; 声明了一个新的数组。我认为这不是你想要的。你需要在构造函数中初始化 this.square - OneCricketeer
你遇到了什么问题? - talex
如果您不需要 int[][],那么我在 此帖子 上提供了一个只使用 List 的答案。 - OneCricketeer
Caitlyn,我很想达到你的期望。你能否回复我的答案并告诉我它是否好? - xenteros
2个回答

2

我看到两种情况:

  1. 用户在开始时给出尺寸
  2. 用户没有给出尺寸。

广告1。
不需要使用 ArrayList。只需按照以下方式读取输入:

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

广告 2.

我会扫描用户输入的数字,只要数字合法。然后检查是否输入了正确数量的数字。然后将其转换为一个整数的平方数组。

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

显然,您需要注意错误处理。如果您有进一步的问题,请在评论中提出。如果您感兴趣,我会更新我的答案。


@CaitlynDaly 在 [so] 上,我们不会写“谢谢”,而是会点赞并标记答案为已接受。如果你想加入社区,我强烈建议阅读 [ask] 和 [mcve]。特别是第二个将教你如何以一种方式提问,以至于我不需要猜测我们正在讨论哪个情况。祝你在 [so] 上好运! - xenteros

0

在确定完全平方数时有一个拼写错误

应该是

if (squared == (int) squared) return true;

如果一个二维数组是完美的平方,你可以初始化并填充它

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接