简体   繁体   English

将列表中的每个值分配给二维数组

[英]assigning each value from the list to a two-dimensional array

I don't really know how to define the assignment of individual elements in the list to 2D array.我真的不知道如何定义列表中单个元素到二维数组的分配。 For example:例如:

I have a list that is String, it contains:我有一个字符串列表,它包含:

list.get(0) = "1 2 3" 
list.get(1) = "1 4 2"

I want each element to be assigned to int[][] like this way:我希望每个元素都像这样分配给int[][]

tab[0][0] = 1;
tab[0][1] = 2;
tab[0][2] = 3;
tab[1][0] = 1;
tab[1][1] = 4;
tab[1][2] = 2;

I prepared such code:我准备了这样的代码:

Scanner scan = new Scanner(System.in);
        List<String> stringToMatrix = new ArrayList<>();

        while (!stringToMatrix.contains("end")) {
            stringToMatrix.add(scan.nextLine());
        }
        stringToMatrix.remove(stringToMatrix.size() - 1);
        //-size of matrix
        int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(" ").length + 1;
        int rows = stringToMatrix.size();
        int[][] bigMatrix = new int[rows+2][col+2]; //rows and cols +2 because I want to insert values from the list into the middle of the table.

        int outerIndex = 1;
        for (String line: stringToMatrix) {
            String[] stringArray = line.split(" ");
            int innerIndex = 1;
            for (String str: stringArray) {
                int number = Integer.parseInt(str);
                bigMatrix[outerIndex][innerIndex++] = number;
            }
            outerIndex++;
        }

        for (int[] x: bigMatrix) {
            System.out.print(Arrays.toString(x));
        }

Input:输入:

1 2 3
1 2 3
end

Result:结果:

[0, 0, 0, 0, 0][0, 1, 2, 3, 0][0, 1, 2, 3, 0][0, 0, 0, 0, 0]

Input:输入:

1 -2 53 -1
1 4 -4 24
end

Result结果

[0, 0, 0, 0, 0, 0, 0, 0, 0][0, 1, -2, 53, -1, 0, 0, 0, 0][0, 1, 4, -4, 24, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0]

The problem was there:问题出在那里:

int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(" ").length + 1;

Here is a small example how to convert it to an 2d int[][] array这是一个如何将其转换为二维 int[][] 数组的小例子

List<String> myListIWantToConvert = new ArrayList<Stirng>();
myListIWantToConvert.add("1 2 3");
myListIWantToConvert.add("1 4 2");

int[][] myConvert = new int[][];

int i = 0;
for(String string : myListIWantToConvert) {
    // create new int array
    int[] arrayToPutIn = new int[];
    // split the string by the space
    String[] eachNumber = string.split(" ");
    // loog through string array
    for(int i2 = 0; i2 < eachNumber.length; i2++) {
        // convert string to integer and put in the new integer array
        arrayToPutIn[i2] = Integer.valueOf(eachNumber[i2]);
    }
    // finally add the new array
    myConvert[i] = arrayToPutIn;
    i++; // edit: ( sry forgot :D )
}

A for-loop with another nested one shall do the thing:与另一个嵌套循环的 for 循环应该做的事情:

List<String> list = ...                           // input list
int[][] tab = new int[2][3];                      // target array

int outerIndex = 0;                               // X-index of tab[X][Y] 
for (String line: list) {                         // for each line...
   String[] stringArray = line.split(" ");        // ... split by a space
   int innerIndex = 0;                            // ... Y-index of tab[X][Y]
   for (String str: stringArray) {                // ... for each item in a line
       int number = Integer.parseInt(str);        // ...... parse to an int
       tab[outerIndex][innerIndex++] = number;    // ...... add to array tab[X][Y]
   }                                                        and increase the Y
   outerIndex++;                                  // ... increase the X
}

Remember, additionally, you might want:请记住,此外,您可能需要:

  • ... to handle the exceptional values (non-parseable into an int) ... 处理异常值(不可解析为 int)
  • ... to split by multiple white characters ( \\\\s+ ), not a single space ...由多个白色字符( \\\\s+ )分割,而不是单个空格
  • ... to handle the array index overflow ... 处理数组索引溢出

The Java 8 Stream API brings the way easier way to do so... if you don't mind Integer[][] as a result instead. Java 8 Stream API 提供了一种更简单的方法……如果您不介意Integer[][]结果。

Integer[][] tab2 = list.stream()                  // Stream<String>
    .map(line -> Arrays.stream(line.split(" "))   // ... Stream<String> (split)
        .map(Integer::parseInt))                  // ... Stream<Integer>
        .toArray(Integer[]::new))                 // ... Integer[]
    .toArray(Integer[][]::new);                   // Integer[][]

Sample Solution:示例解决方案:

import java.util.*;
public class Main {
public static void main(String []args){
    
        List<String> tempList = new ArrayList<>();
        tempList.add("1 2 3");
        tempList.add("1 4 2");
        
        int[][] resultArr = new int[tempList.size()][3];//Initialzing the 2d array
        
        for (int i = 0; i < resultArr.length; ++i) {//Assigning the elements to 2D Array
             String[] tempArr = tempList.get(i).split(" ");
            for(int j = 0; j < resultArr[i].length; ++j) {
               
                resultArr[i][j] =Integer.parseInt(tempArr[j]);
               
            }
        }
        for (int i = 0; i < resultArr.length; ++i) {//Printing the newly created array elements
             String[] temparr = tempList.get(i).split(" ");
            for(int j = 0; j < resultArr[i].length; ++j) {
               
                System.out.println(resultArr[i][j]);
               
            }
        }
     }

}

Output: 1 2 3 1 4 2输出: 1 2 3 1 4 2

Take care of the int array size.注意int数组的大小。 If the list contains different number of elements, you should consider the following:如果列表包含不同数量的元素,则应考虑以下事项:

import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("1 2 3");
    list.add("4 5 6 7");
    
    int[][] tab = new int[list.size()][];
    
    for(int i = 0; i < list.size(); i++) {
      String[] value = list.get(i).split(" ");
      tab[i] = new int[value.length];
      for(int j = 0; j < value.length; j++) { 
        tab[i][j] = Integer.parseInt(value[j]);
      }
      System.out.println( Arrays.toString(tab[i]));
    }
  }
}

You must pay attention on the "dimension" definition.您必须注意“维度”的定义。

When working with 2 dimensional arrays it's an array that contains array, an 2x3 dimension array would looks like that:当处理二维数组时,它是一个包含数组的数组,一个 2x3 维数组看起来像这样:

[[x,y,z]] 
[[a,b,c]]

In a more helpful visualization:在更有用的可视化中:

[] item 1 of 2 of first dimension
  [x,y,z] the 3 items of the second dimension
[] item 1 of 2 of first dimension
  [a,b,c] the 3 items of the second dimension

Now imagine that the list is a 1 dimension array, if your example we could make it like that:现在想象这个列表是一个一维数组,如果你的例子我们可以这样:

["1 2 3"]["1 4 2"]

So let's change now the Strings to an array of chars所以现在让我们将字符串更改为字符数组

[['1','2','3']]
[['1','4','2']]

or或者

[]
  ['1',' ','2',' ','3']
[]
  ['1',' ','4',' ','2']

Can you see the similarities?你能看出相似之处吗?

Now to get what you want we need to remove the white spaces and to transform them into Integers.现在为了得到你想要的东西,我们需要删除空格并将它们转换为整数。

So your algorithm would be:所以你的算法是:

Create a new array of the desired dimensions (2x3) in your
define two variables to hole the value for line and column index with 0 value
loop over the list of strings:
  transform this line in a array of strings, splinting it by ' '
    loop over the splinted values and convert them to int
    add your converted value in array[line][column]
    increase column by 1
  increase line by 1
  set column value to 0

Try it out and have fun :D试试看,玩得开心 :D

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

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