Java Reference
In-Depth Information
Here is a complete program that puts these pieces together. It also uses printf
statements to format the output and includes a header for the table and a total afterward:
1 // This program finds the distribution of leading digits in a set
2 // of positive integers. The program is useful for exploring the
3 // phenomenon known as Benford's Law.
4
5 import java.io.*;
6 import java.util.*;
7
8 public class Benford {
9
public static void main(String[] args)
10
throws FileNotFoundException {
11
Scanner console = new Scanner(System.in);
12
System.out.println("Let's count those leading digits...");
13
System.out.print("input file name? ");
14
String name = console.nextLine();
15
Scanner input = new Scanner( new File(name));
16
int [] count = countDigits(input);
17
reportResults(count);
18
}
19
20 // Reads integers from input, computing an array of counts
21 // for the occurrences of each leading digit (0-9).
22 public static int [] countDigits(Scanner input) {
23 int [] count = new int [10];
24 while (input.hasNextInt()) {
25 int n = input.nextInt();
26 count[firstDigit(n)]++;
27 }
28 return count;
29 }
30
31 // Reports percentages for each leading digit, excluding zeros
32 public static void reportResults( int [] count) {
33 System.out.println();
34 if (count[0] > 0) {
35 System.out.println("excluding " + count[0] + " zeros");
36 }
37 int total = sum(count) - count[0];
38 System.out.println("Digit Count Percent");
39 for ( int i = 1; i < count.length; i++) {
40 double pct = count[i] * 100.0 / total;
41 System.out.printf("%5d %5d %6.2f\n", i, count[i], pct);
42 }
Search WWH ::




Custom Search