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

huangapple go评论75阅读模式
英文:

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

问题

我不太知道如何定义将列表中的各个元素分配到2D数组中的任务。例如:

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

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);
//-矩阵的大小
int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(" ").length + 1;
int rows = stringToMatrix.size();
int[][] bigMatrix = new int[rows+2][col+2]; //行和列+2,因为我想将列表中的值插入到表的中间。

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;
英文:

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) = &quot;1 2 3&quot; 
list.get(1) = &quot;1 4 2&quot;

I want each element to be assigned to int[][] like this way:

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&lt;String&gt; stringToMatrix = new ArrayList&lt;&gt;();

        while (!stringToMatrix.contains(&quot;end&quot;)) {
            stringToMatrix.add(scan.nextLine());
        }
        stringToMatrix.remove(stringToMatrix.size() - 1);
        //-size of matrix
        int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(&quot; &quot;).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(&quot; &quot;);
            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(&quot; &quot;).length + 1;

答案1

得分: 1

这是一个小例子,展示了如何将其转换为一个二维 int[][] 数组:

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

int[][] myConvert = new int[myListIWantToConvert.size()][];

int i = 0;
for (String string : myListIWantToConvert) {
    // 创建新的整数数组
    String[] eachNumber = string.split(" ");
    int[] arrayToPutIn = new int[eachNumber.length];
    
    // 遍历字符串数组
    for (int i2 = 0; i2 < eachNumber.length; i2++) {
        // 将字符串转换为整数并放入新的整数数组
        arrayToPutIn[i2] = Integer.valueOf(eachNumber[i2]);
    }
    
    // 最后添加新数组
    myConvert[i] = arrayToPutIn;
    i++;
}

注意:我已经根据您的要求,仅返回翻译后的内容,不包含其他额外的内容。

英文:

Here is a small example how to convert it to an 2d int[][] array

List&lt;String&gt; myListIWantToConvert = new ArrayList&lt;Stirng&gt;();
myListIWantToConvert.add(&quot;1 2 3&quot;);
myListIWantToConvert.add(&quot;1 4 2&quot;);

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(&quot; &quot;);
    // loog through string array
    for(int i2 = 0; i2 &lt; 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 )
}

答案2

得分: 1

一个带有嵌套循环的for循环可以完成这个任务:

List<String> list = ...                          // 输入列表
int[][] tab = new int[2][3];                      // 目标数组

int outerIndex = 0;                               // tab[X][Y]的X索引
for (String line: list) {                         // 对于每一行...
   String[] stringArray = line.split(" ");        // ... 通过空格分割
   int innerIndex = 0;                            // tab[X][Y]的Y索引
   for (String str: stringArray) {                // ... 对于每个行中的元素
       int number = Integer.parseInt(str);        // ...... 解析为整数
       tab[outerIndex][innerIndex++] = number;    // ...... 添加到数组tab[X][Y]
   }                                                        并增加Y
   outerIndex++;                                  // ... 增加X
}

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

  • ... 处理异常值(无法解析为整数的情况)
  • ... 使用多个空白字符进行分割(\\s+),而不仅仅是单个空格
  • ... 处理数组索引溢出

如果你不介意结果为Integer[][],Java 8 Stream API 提供了更简单的方法来实现...

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

A for-loop with another nested one shall do the thing:

List&lt;String&gt; 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(&quot; &quot;);        // ... 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)
  • ... to split by multiple white characters (\\s+), not a single space
  • ... 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.

Integer[][] tab2 = list.stream()                  // Stream&lt;String&gt;
    .map(line -&gt; Arrays.stream(line.split(&quot; &quot;))   // ... Stream&lt;String&gt; (split)
        .map(Integer::parseInt))                  // ... Stream&lt;Integer&gt;
        .toArray(Integer[]::new))                 // ... Integer[]
    .toArray(Integer[][]::new);                   // Integer[][]

答案3

得分: 1

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

英文:

Sample Solution:

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

}

Output:
1
2
3
1
4
2

答案4

得分: 1

处理 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]));
    }
  }
}
英文:

Take care of the int array size. 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&lt;String&gt; list = new ArrayList&lt;&gt;();
    list.add(&quot;1 2 3&quot;);
    list.add(&quot;4 5 6 7&quot;);
    
    int[][] tab = new int[list.size()][];
    
    for(int i = 0; i &lt; list.size(); i++) {
      String[] value = list.get(i).split(&quot; &quot;);
      tab[i] = new int[value.length];
      for(int j = 0; j &lt; value.length; j++) { 
        tab[i][j] = Integer.parseInt(value[j]);
      }
      System.out.println( Arrays.toString(tab[i]));
    }
  }
}

答案5

得分: 1

你必须注意 "维度" 的定义。

在处理二维数组时,它是一个包含数组的数组,一个2x3维数组看起来像这样:

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

更有帮助的可视化:

[] 第一维的第1个项目
  [x,y,z] 第二维的3个项目
[] 第一维的第2个项目
  [a,b,c] 第二维的3个项目

现在想象一下,如果列表是一个一维数组,根据你的示例,我们可以这样表示:

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

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

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

或者

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

你能看到相似之处吗?

现在,为了获得你想要的结果,我们需要去除空格并将它们转换为整数。

所以你的算法将是:

在你的代码中创建一个新的数组,具有所需的维度(2x3)
定义两个变量来保存行索引和列索引的值,初始值为0
遍历字符串列表:
  将此行转换为字符串数组,通过空格进行分割
    遍历分割后的值并将它们转换为整数
    将转换后的值添加到数组
[column]
增加 column 的值 1 增加 line 的值 1 将 column 的值设置为 0

试一试,玩得开心 将列表中的每个值分配到二维数组中。

英文:

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:

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

[&quot;1 2 3&quot;][&quot;1 4 2&quot;]

So let's change now the Strings to an array of chars

[[&#39;1&#39;,&#39;2&#39;,&#39;3&#39;]]
[[&#39;1&#39;,&#39;4&#39;,&#39;2&#39;]]

or

[]
  [&#39;1&#39;,&#39; &#39;,&#39;2&#39;,&#39; &#39;,&#39;3&#39;]
[]
  [&#39;1&#39;,&#39; &#39;,&#39;4&#39;,&#39; &#39;,&#39;2&#39;]

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 &#39; &#39;
    loop over the splinted values and convert them to int
    add your converted value in array
[column] increase column by 1 increase line by 1 set column value to 0

Try it out and have fun 将列表中的每个值分配到二维数组中。

huangapple
  • 本文由 发表于 2020年10月21日 17:25:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64460592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定