java - 从文件到数组的直方图
问题描述
我基本上是java和编程的初学者,我有这个问题。我有一个文件(其中包含从 0 到 10 的随机数),我需要将它存储到数组 B[i], i=0...10 中,这样 B[0] 包含零个数,B[ 1] 1 的数量等。例如,如果我的文件中有三个“1”,则 B[1] = 3。我创建了以下代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hist {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("in.txt");
Scanner sc = new Scanner(file);
int[] B = new int [10];
for (int i = 0; i < 10; i++) {
int sum = 0;
while(sc.hasNextLine()){
int k = sc.nextInt();
System.out.println(i); //control line
if(i==k){
sum=sum+1;
B[i] = sum;
}
}
}
sc.close();
for (float x : B) {
System.out.println(x); //just to see how B looks like
}
}
}
作为输出,我得到了 20 个零。所以似乎我的代码没有遍历 i,但我不明白为什么。
解决方案
如果文件只包含 int 值,则不需要逐行读取。
int[] B = new int [10];
File file = new File("in.txt");
try (Scanner sc = new Scanner(file)) { // use try-with-resources to close scanner automatically
while (sc.hasNextInt()) {
B[sc.nextInt()]++;
}
System.out.println("histogram: " + Arrays.toString(B));
}
注意:如果文件中的数字是从 0 到 10 (含),则 的大小B
必须为 11。
更新
如果直方图需要显示为 2 个数组,其中第一个数组计算 1 到 5 的值,第二个数组计算 6 到 10 的值,这可以简单地实现:
int[] count1to5 = new int[5];
int[] count6to10 = new int[5];
File file = new File("in.txt");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextInt()) {
int n = sc.nextInt();
// select the counting array
int[] receiver = n > 5 ? count6to10 : count1to5;
receiver[(n - 1) % 5]++; // correct index by 1
}
System.out.println("histogram 1 to 5: " + Arrays.toString(count1to5));
System.out.println("histogram 6 to 10: " + Arrays.toString(count6to10));
}
类似地,二维数组可用于为介于值之间的连续数字范围构建直方图,min
并将其max
划分为length
值的子范围:
int min = 1;
int max = 10;
int length = 5;
int subranges = (int) Math.ceil((max + 1.0 - min) / length);
int[][] histogram = new int[subranges][length];
File file = new File("in.txt");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextInt()) {
int n = sc.nextInt() - min; // shift index by min
// select the subrange
int[] receiver = histogram[n / length];
receiver[n % length]++; // correct index inside row
}
for (int i = 0; i < histogram.length; i++) {
for (int j = 0; j < histogram[i].length; j++) {
System.out.printf("%2d=%2d ", i * length + j + min, histogram[i][j]);
}
System.out.println();
}
}
推荐阅读
- macos-high-sierra - Mac OS X 10.x 网络服务通知
- java - Android Room 库错误:找不到字段的吸气剂
- python - 根据自定义范围离散化 Pandas 列
- python - 返回错误答案的字谜代码
- ruby - 如何拆分哈希并将其作为 ruby 中的两个单独参数传递?
- rxjs - 如何在 RxJS 中做不同的油门
- angular - 自定义 Stackblitz Angular 项目模板
- c# - Visual Studio 构建错误:项目中不存在目标“MainResourceGeneration”
- backup - Nexus 3 备份 - 我可以只备份 /nexus-data 吗?
- webpack - workbox-webpack-plugin 与离线插件之间的区别?