Reputation: 21
I'm working on an assignment for my computer course and our task is to write a method that analyzes the array "numbers" and return an array representing for each digit, the proportion of times it occurred as a leading digit...
ie { 100, 200.1, 9.3, 10} then 1 occurs as a leading digit 50 % of the time, 2 occurs 25% of the time, and 9 occurs 25 % of the time, so your produced array should contain: {0, .5, .25, 0, 0, 0, 0, 0, 0, .25}
I'm having issues getting started, it's suggested that we write a helper method called, for example, countLeadingDigits which returns an array of counts for each digit and only then calculate the percentages. I don't know how to go about writing the method that takes an unknown number of input doubles from the user then store the number of times each digit appears as a leading digit.. I've already written the part of the code that calculates the leading digit. Any hints pleasee?
Upvotes: 2
Views: 351
Reputation: 25950
A solution with short and intense code:
public static void main(String[] args)
{
double[] inputs = { 100, 200.1, 9.3, 10 , -100 }; // your inputs
double sum = inputs.length;
int[] leadingDigitCounters = new int[10]; // counters for 0...9
// Here is how you increment respective leading-digit counters
for (double d : inputs)
{
int j = Integer.parseInt((d + "").replace("-", "").charAt(0) + "");
leadingDigitCounters[j]++;
}
// Printing out respective percentages
for (int i : leadingDigitCounters)
System.out.print((i / sum) + " ");
}
Output:
0.0 0.6 0.2 0.0 0.0 0.0 0.0 0.0 0.0 0.2
Upvotes: 1