繁体   English   中英

如何在Java中将ArrayList更改为2D数组

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

我应该制作一个测试用户输入矩阵的程序是一个魔术方块。 基本上我应该将用户输入放入一个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. 用户在开头给出大小
  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。

我只是扫描数字,因为用户给出了数字。 然后检查他是否给出了适当数量的数字。 然后转换为int的正方形数组。

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

显然你需要注意错误处理。 如果您还有其他问题,请在评论中提问。 如果你有兴趣,我会更新我的答案。

确定完美的广场有一个错字

它应该是

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

如果它是一个完美的正方形,你可以初始化和填充2D数组

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM