首页 > 解决方案 > 从文件到数组的直方图

问题描述

我基本上是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,但我不明白为什么。

标签: javaarrayshistogram

解决方案


如果文件只包含 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();
    }
}

推荐阅读