gpt4 book ai didi

java - 将文本文件转换为二维数组

转载 作者:行者123 更新时间:2023-11-30 07:46:10 27 4
gpt4 key购买 nike

我需要获取一个如下所示的文本文件,并根据其中的数字创建一个二维数组。但是,它需要非常通用,以便它可以应用于条目比此多或少的文本文件。

1 1 11  
1 2 32
1 4 23
2 2 24
2 5 45
3 1 16
3 2 37
3 3 50
3 4 79
3 5 68
4 4 33
4 5 67
1 1 75
1 4 65
2 1 26
2 3 89
2 5 74

这是我到目前为止所拥有的,但当我打印它时它只是给我全零。

import java.util.*;

public class MySales11 {
//variables
private ArrayList<String> list = new ArrayList<>();
private int numberOfEntries;
private int [][] allSales;

//constructor
public MySales11 (Scanner scan) {
//scan and find # of entries
while (scan.hasNext()){
String line = scan.nextLine();
list.add(line);
}
//define size of AllSales array
allSales = new int[list.size()][3];
//populate AllSales array with list ArrayList
for(int a = 0; a < allSales.length; a++){
String[] tokens = list.get(a).split(" ");
for(int b = 0; b < tokens.length; b++){
allSales[a][b] = Integer.parseInt(tokens[b]);
}
}
}
}

最佳答案

当您想要创建大小为 numOfEntries 的数组时,您会读取所有行。

while (scan.hasNext()) {
scan.nextLine();
numberOfEntries++;//this reads all the lines but never stores
}
allSales = new int[numberOfEntries][3];
while (scan.hasNext()) {//input is empty
//the execution never comes here.
}

现在输入为空。所以它永远不会向数组添加值。

<小时/>

您可以使用动态的arrayList - 无需计算行数。

ArrayList<String> list = new ArrayList();
while (scan.hasNext()) {
String s = scan.nextLine();
list.add(s);
}

int [][] myArray = new int[list.size()][3];

for(int i = 0; i < myArray.length; ++i)
{
String[] tokens = list.get(i).split("\\s+");//extra spaces
for(int j = 0; j < tokens.length; ++j)
{
myArray[i][j] = Integer.parseInt(tokens[j]);
}
}

关于java - 将文本文件转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931672/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com