gpt4 book ai didi

java - 使用包含 double 的数组填充数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:50 25 4
gpt4 key购买 nike

我正在处理一个类作业,我们只能使用数组而不能使用 Collection 类来读取文本文件并使用文本文件中的信息填充数组。文件 ArrayData.txt 的信息如下。该文件的格式如下:

3                 //First line states how many sets are in the file
2 //Next line:there are x numbers in the set
10.22 567.98 //Next Line states the doubles that are in the set
//The pattern continues from there
1 // x numbers in the next set
20.55 // Double in the set
3
20.55 2.34 100.97

我的问题是用一个数组填充初始数组,然后用 double 填充第二个数组。

本质上,我希望它看起来像这样:

initArray[0]=> smallArray[2]={10.22,5.67.98} 
initArray[1]=> smallArray[1]={20.55}
initArray[2]=> smallArray[3]={20.55,2.34,100.97}

这是我到目前为止所拥有的:

    public static double[] largeArray;
public static double[] insideArray;
public static void main(String[] args) {

String fileInputName = "ArrayData.txt";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
while (sc.hasNextLine()) {


int i = sc.nextInt();
largeArray= new double[i];
for(int x=0; x<i;x++)
{
int z = sc.nextInt();

insideArray= new double[z];
for(int y=0; y<z; y++)
{
insideArray[z]=sc.nextDouble();
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (sc != null)
sc.close();
}
}

首先,这个逻辑有道理吗?其次,我不断收到数组越界错误,所以我知道有些东西是对的,我只是不确定在哪里。

最佳答案

删除while。您希望主体只执行一次。文件末尾的换行符可能会导致它再次运行,然后就不会出现nextInt()。如果您想支持空文件,请将其设为 if

其次,insideArray[z] = ... 应该是 insideArray[y] = ...

最后,largeArray 应该是一个数组的数组 double[][](所谓的锯齿状数组),并且您希望在填充后将 insideArray 分配给相应的位置。

关于java - 使用包含 double 的数组填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39421838/

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