在我的java程序中添加百分比的好方法是什么?

时间:2018-05-02 18:20:44

标签: java

我必须编写一个Java类来实现Benford's Law

我无法弄清楚如何做最后一部分:“对于每个数字,输出它显示为第一个数字的百分比”

请问我能得到一些帮助吗?

import java.io.FileNotFoundException;

import java.util.Scanner;

import java.io.File;

public class BenfordLaw {
public static void main(String[] args) {

    String[] arrayOfData = new String[125];//Array creation
    // Read inn from the text file
    Scanner input = null;



    try {
        input = new Scanner(new File("worldPopulations.csv"));//instantiation

    } 
    catch (FileNotFoundException e) {
        System.out.println("File was not found");
        e.printStackTrace();
        System.exit(0);

    }//end try catch block
    input.nextLine(); //so we can skip it

    int index = 0;
    while(input.hasNextLine()) {
        String line = input.nextLine();
        //System.out.println(Line);
        arrayOfData[index] = line;
        index++;

    }
    input.close();

    int[] count = new int[9];//setting limit for array


    //Now process our data
    for(int i = 0; i < arrayOfData.length; i++) {
        System.out.println(arrayOfData[i]);//tests to see that we filled the array correctly
        //find the first char in our string
        char firstChar = arrayOfData[i].charAt(0);
        int firstDigit = firstChar - '0';
        System.out.println(firstDigit);
        count[firstDigit - 1]++;

    }//end arrayOfData.length

    //look at the count of each digit
    for (int i = 0; i < count.length; i++) {
        System.out.println("Number of digit" + (i+1) + "'s is " + count[i] );
    }



}//end main

}//end class

1 个答案:

答案 0 :(得分:1)

你非常接近解决方案。您有$entries = $client->entries([ 'pageSize' => 100 ]); foreach ($entries->iterateByPage() as $page) { print count($page); // Should be 100 } 数组,其中包含数据集中每个数字(1-9)显示为第一个数字的次数。如果你对这些计数求和(使用循环),那么你可以在计算每个数字的百分比(计数/总数* 100)时使用该总数作为分母。

确保在进行除法之前将计数转换为浮点数,否则您将从整数除法中得到截断的结果。