首页 > 解决方案 > 我可以从文件中保存超过数组大小的数字吗?

问题描述

问题是假设数组最多可以存储 5 个数字。即使文件中有超过 5 个值,您的方法也需要确保从文件中读取最多 5 个数字。您不能假设文件中总是有 5 个值。该方法不应再将值显示到屏幕上。但是当我保存我的值超过 5 个数字时,我收到错误消息是索引 5 超出了长度 5 的范围。

System.out.println("Input the file name");
names = ff.nextLine();

try {
    File f = new File(names);
    Scanner inputFile = new Scanner(f);
            
    while (inputFile.hasNext()) { // get how many number we have
        inputFile.nextInt();     
        line++;             
    }
    
    Scanner inputFile2 = new Scanner(f); // scanner all the number and save to array
    for (int i = 0; i < line; i++) {
        store[i] = inputFile2.nextInt();
    }

    inputFile.close();
} catch (IOException e) {
    System.out.println("The file is not exit"); // if cannot find the file
}

文件值为 1-10,如何只使用数组在数组中保存 5 个值?

标签: javaarrays

解决方案


while (inputFile.hasNext()) {  // get how many number we have
    inputFile.nextInt();     
    line=line+1;                
}

好吧,这看起来像你在计算行号(你不需要这样做,但我看到了你的方法)。在你的例子中,你说有 10 行,所以line等于 10。但是你这样做:

for(int i=0;i<line;i++) {
    store[i]=inputFile2.nextInt();
}

这段代码将每个 int 放在数组的下一个位置10 次,因为line是 10。您没有显示如何初始化数组,但我猜它的长度为 5。这意味着,当i= 5 in你的for循环,没有第5个位置可以将任何东西放入你的数组中,所以你会得到一个ArrayIndexOutOfBoundsException。你想要做的是:

for(int i = 0; i < Math.min(line, stores.length); i++) {
    store[i]=inputFile2.nextInt();
}

相反,此代码将在更小的数组长度或文件中的行数处停止循环。在这种情况下,stores.length将是 5,因此您将从 0 到 4 填充数组 5 次。如果在另一种情况下,您有一个长度为 15 的数组(并且line仍然是 10),Math.min(line, stores.length)将返回line保持的值,即10,所以它只会填充到数组中的第 10 位,其余的都是 0(假设它是一个int[])。


推荐阅读