java - 为什么我的程序没有读取文本文件中的第一个整数?
问题描述
我已经完成了方法,它找到了带有成绩的 txt 文件,读取它们,然后将它们放入一个数组中,然后输出我们需要的指定值。出于某种原因,它没有采用所有整数。例如,如果我输入:
6、87、23、90
它只会读取最后三个。
87、23 和 90
//reads the data from the file
private static int[] readExamScores(String userFile) throws FileNotFoundException{
File inputFile = new File(userFile);
Scanner stats = new Scanner(inputFile);
try{
int scores[] = new int[stats.nextInt()];
int i = 0;
while (stats.hasNext()){
scores[i] = stats.nextInt();
i++;
}
System.out.println("\n" + "There are " + (i) + " scores. \n");
Arrays.sort(scores);
return scores;
}
finally {
stats.close();
}
}
解决方案
因为您的索引由于 init 和同时递增而已经移动了 1,例如 stats.nextInt()
我建议将 arraylist 修复为扫描仪“使用”如果您计算字符串行中的令牌或读取它返回的内容。
List<Integer> scores = new ArrayList<Integer>()
int i = 0;
while (stats.hasNext()){
scores.add(stats.nextInt());
i++;
}
推荐阅读
- prisma - Prisma 模式 - 从多个可能的外键(或关系)创建关系字段
- python-3.x - 如何使用 cv2.VideoWriter 输出 x265 压缩视频
- r - R - 根据不断变化的列条件,通过对变量进行分组来增加变量
- osgi - 为什么 bnd 工作区模型中的存储库不支持传递依赖?
- c++ - 如果输入在c ++中无效,则重新提示
- java - JTable 将整数排序为字符串
- java - 处理 - 构造函数 ArrayList
(类)不存在 - r - XBRL R 包读取添加另一个链接到输入链接。导致无法打开的链接
- spring-boot - 使用 Consul 和 Spring Cloud Consul 的多集群 Kubernetes 服务发现
- node.js - Node.js:fs unlink vs. fs-extra remove 删除文件。什么时候选择哪一个,为什么?