java - 我可以从文件中保存超过数组大小的数字吗?
问题描述
问题是假设数组最多可以存储 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 个值?
解决方案
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[]
)。
推荐阅读
- python - 在 Python 3.x 中从另一个类调用类方法
- python - 单击提交按钮后,Django 表单应保持不变
- reactjs - 类型错误:更新时无法读取未定义反应 redux 的属性“地图”
- angular - 加载所有子内容时显示父组件角度4
- python - 在底图上使用倒钩绘制风时不显示
- python - 使用 Python 登录网站
- php - php 查询不使用 UTF-8 字符集
- php - WordPress有什么方法或任何片段来最小化标签'style amp-custom'中指定的样式表的渲染大小?
- git - 无法通过 GoDaddy 的 SMTP 服务器使用 Git 命令发送电子邮件
- java - 在 Android 中读取内部存储文件花费了太多时间