【问题标题】:assigning each value from the list to a two-dimensional array将列表中的每个值分配给二维数组
【发布时间】:2020-10-21 09:25:58
【问题描述】:

我真的不知道如何将列表中的单个元素分配给二维数组。例如:

我有一个字符串列表,它包含:

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

我希望像这样将每个元素分配给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;

我准备了这样的代码:

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

输入:

1 2 3
1 2 3
end

结果:

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

输入:

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

结果

[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]

问题就在那里:

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

【问题讨论】:

  • 在找到 space(" ") 的地方拆分列表中的每个元素,并将拆分的部分存储在另一个一维数组中。例如 num = [1,2,3,1,4,2]。然后使用嵌套循环访问 2D 数组的索引,并将 1D 数组中的元素插入其中。

标签: java arrays list


【解决方案1】:

一个带有另一个嵌套循环的 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
}

记住,另外,你可能想要:

  • ... 处理异常值(不可解析为 int)
  • ... 由多个白色字符 (\\s+) 分割,而不是单个空格
  • ...处理数组索引溢出

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[][]

【讨论】:

  • 谢谢,这超出了我的预期。
  • 但是如果我有像 -12, 2356 这样的数字呢?
  • 你没有指定!您必须向我们提供所有信息才能获得有效答案。但是,您是否尝试过代码?我敢打赌,只要 ` `(空格)的分割保持不变并且 Integer.parseInt(...) 可以处理负数,它就可以工作。
  • 你是对的,不幸的是我没有预见到这一点,直到代码通过测试...代码经过测试,负数和 num > 9 导致奇怪的结果
  • 什么是奇怪的结果。输入看起来如何(完整)。请更新问题。
【解决方案2】:

这是一个小例子,如何将其转换为 2d 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 )
}

【讨论】:

    【解决方案3】:

    示例解决方案:

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

    输出: 1 2 3 1 4 2

    【讨论】:

      【解决方案4】:

      你必须注意“维度”的定义。

      当使用二维数组时,它是一个包含数组的数组,一个 2x3 维数组看起来像这样:

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

      在更有用的可视化中:

      [] 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
      

      现在假设列表是一维数组,如果您的示例可以这样:

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

      现在让我们将字符串更改为字符数组

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

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

      你能看出相似之处吗?

      现在要得到你想要的,我们需要删除空格并将它们转换为整数。

      所以你的算法是:

      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
      

      试试看,玩得开心:D

      【讨论】:

        【解决方案5】:

        注意int 数组的大小。如果列表包含不同数量的元素,您应该考虑以下几点:

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

        【讨论】:

          猜你喜欢
          • 2018-04-11
          • 1970-01-01
          • 2023-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-13
          相关资源
          最近更新 更多