java Java如何将一维数组转换为二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31387022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:31:21  来源:igfitidea点击:

How to convert a one-dimensional array to two-dimensional array in Java

javaarrays

提问by Priyadharshini Ravi

I would like to read a file which is in the form of a matrix, so i tried reading a file put it in String arraylist and then converted to integer array. Now I need a 2D integer array. Can anyone help? Is there any better way to do this.

我想读取一个矩阵形式的文件,所以我尝试读取一个文件,将它放在 String arraylist 中,然后转换为整数数组。现在我需要一个二维整数数组。任何人都可以帮忙吗?有没有更好的方法来做到这一点。

public class readMat {

private static ArrayList<String> list = new ArrayList<String>();

  public static void main (String[] args)
     {
          // read file and put in arraylist
         try 
            {
        Scanner s = new Scanner(new File("link_info_test.txt"));

        while (s.hasNext())
         {
          list.add(s.next()); 

        }

    } 
    catch (Exception e)
       {
        e.printStackTrace();            
       }
    String[] stockArr = new String[list.size()];
    stockArr = list.toArray(stockArr);
    int[] sum= Convert(stockArr);       

       }
      // convert string arraylist to integer 1 dimensional array    private static int[] Convert(String[] stockArr)
     {
             if (list != null)
           {
           int intarray[] = new int[stockArr.length];
           for (int i = 0; i < stockArr.length; i++) 
           {
           intarray[i] = Integer.parseInt(stockArr[i]);
           }
           return intarray;
           }
           return null;
         }

     }

回答by Lee Presswood

After the line

线后

int[] sum= Convert(stockArr); 

you have your entire file in a 1D array of integers. At this point, you have to determine the width and height of the 2D array.

您将整个文件放在一维整数数组中。此时,您必须确定二维数组的宽度和高度。

Let's say you want the 2D array to have 3 rows and 4 columns as an example. Do this:

假设您希望二维数组具有 3 行 4 列作为示例。做这个:

int[][] int_table = new int[3][4];
for(int j = 0; j < 3; j++)
{  
   for(int i = 0; i < 4; i++)
   {
      int_table[j][i] = sum[j * 4 + i];
   }
}

The equation I'm using within sum's index is a conversion function that goes from 1D to 2D coordinates. Starting at both j and i being equal to 0, sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]. The variable i would increment by one at the next step, and we would have sum[0 * 4 + 1] = sum[1]. At the end of the row, i would reset to 0 and j would increment by 1. At that point, we would have sum[1 * 4 + 0] = sum[4], or sum's fifth element. This makes sense if you consider the first four elements as those of the first row. now that we're on a new row, we can fill it with the next four. The "four" that I've been mentioning is the width of the row that we defined earlier while declaring the 2D array.

我在 sum 索引中使用的方程是一个从一维坐标到二维坐标的转换函数。从 j 和 i 都等于 0 开始,sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]。变量 i 将在下一步增加 1,我们将得到 sum[0 * 4 + 1] = sum[1]。在行的末尾,i 将重置为 0,j 将递增 1。此时,我们将得到 sum[1 * 4 + 0] = sum[4],或 sum 的第五个元素。如果您将前四个元素视为第一行的元素,则这是有道理的。现在我们在一个新行上,我们可以用接下来的四个来填充它。我一直提到的“四”是我们之前在声明二维数组时定义的行的宽度。

Keep in mind that the 2D array's width and height can't multiply together to be larger than the total number of integers in the 1D array. You'll get an IndexOutOfBoundsException if you try to read beyond that size.

请记住,二维数组的宽度和高度不能相乘以大于一维数组中整数的总数。如果您尝试读取超出该大小的内容,您将收到 IndexOutOfBoundsException。

回答by Kamran

Let's say you have temperature data for each day of the week for 10 weeks (that is 70 pieces of data). You want to convert it to a 2d array with rows representing weeks and columns representing days. Here you go:

假设您有 10 周内一周中每一天的温度数据(即 70 条数据)。您想将其转换为二维数组,其中行表示周,列表示天。干得好:

int temp[70] = {45, 43, 54, ........}
int twoD[30][7]

for(int i=0; i < 70; i++) {
   twoD[i / 7][i % 7] = temp[i]
}

That's it.

而已。

回答by ArtforLife

Assuming that each entry of your String array consists of some integers, separated by some delimiter (comma, dot, hyphen, etc), then you can use the String.split() method. For instance, if your delimiter is a comma, then you would do something like this:

假设您的 String 数组的每个条目由一些整数组成,由一些分隔符(逗号、点、连字符等)分隔,那么您可以使用 String.split() 方法。例如,如果您的分隔符是逗号,那么您将执行以下操作:

String Integer1;
String Integer2;
String[] TotalString;
TotalString = stockArr[i].Split(",");
Integer1 = TotalString[0];
Integer2 = TotalString[1];

Then just parse the Strings into integers and put them into your array.

然后只需将字符串解析为整数并将它们放入您的数组中。

回答by Waqas Ikram

If i understood, your question correctly you want to convert 1D array to 2D array ... You can use following method

如果我理解,你的问题是正确的,你想将一维数组转换为二维数组......你可以使用以下方法

public static int[][] convertArrayTo2DArray(final int[] _1darray) {
    int[][] _2dArray = null;
    int size = _1darray.length / 2;
    if (_1darray.length % 2 == 0) {
        _2dArray = new int[2][size];
    } else {
        _2dArray = new int[3][size];
    }

    int index = 0;
    outter: for (int i = 0; i < _2dArray.length; i++) {
        for (int j = 0; j < _2dArray[i].length; j++) {
            if (index == _1darray.length) {
                break outter;
            }
            _2dArray[i][j] = _1darray[index];
            index++;
        }
    }
    return _2dArray;
}