1. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Code to sort the leading digit of a number.

Hello Guys,

So I have been given an assignment by my teacher to create a program that takes a bunch of data and sorts them by the leading digit. By this I mean it finds the leading digit of a number (e.g. 260 leading digit: 2) and then will increase the count of the array for "2" by one (yes im horrible at explaining this). So here is what I have so far.

Java Code:
```import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BenfordsLaw {

public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub

Scanner input = new Scanner(new File("spanish-city-pop.txt"));
System.out.println("Digit\tCount\t%");
while (input.hasNextInt()) {
int next = input.nextInt();
// process next

int array[]={next};

for(int counter = 0; counter<array.length;counter++){

System.out.println(counter + "\t" + array [counter]);

}

}
}
}```
Yes I know all this does is print out all the digits in the txt document. I have no clue where to start so for now I really need to just find a way to get the leading digit of each number. Anyone have any recommendations?

What is required by the end of the program:
1) Create a project in Eclipse called Benford with a class named Benford (make sure you have the main method check box!)
2) Your project should read in the data from a ﬁle called data.txt - you can put any data you want in the ﬁle, such as US population numbers over the past 100 years, etc. Just make sure all of the data is of type integer! This ﬁle should be located in your project folder, NOT THE SRC.
3) Your project then should determine for each number what the leading digit is, and tally the results in an array of appropriate length.
4) Finally, you should display the results in a table.
Last edited by CreatingDrake; 11-30-2013 at 09:12 PM.

2. ## Re: Code to sort the leading digit of a number.

Would this be the correct order for sorted numbers: 11111 22 3333333 4 55
What does this mean: count of the array for "2" by one ?

What would the results printed by the program look like?

3. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

Okay well I will try to split it up I have worked on the code and am getting an "type mismatch" saying it cant convert from int to int[].
Here is the code:
Java Code:
```public static int[] countDigits(Scanner input) {
int[] count = new int[10];
int i = input.nextInt();
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
}```
why am I getting this error?

4. ## Re: Code to sort the leading digit of a number.

cant convert from int to int[].
You can't convert an int to an array of int. The method is defined to return an array of int. The abs() method does not return an array.

Either change what the method is defined to return to an int
or have the method return an int array.

5. Senior Member
Join Date
Jan 2013
Location
United States
Posts
2,722
Rep Power
4

## Re: Code to sort the leading digit of a number.

Sounds like a frequency count too me, counting numbers based on their first digit.

Regards,
Jim

6. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

Okay now I have to make a few lines of code that return the first nonzero digit of a string, 0 if no such digit found. I was thinking of something like this.
Java Code:
``` public static int firstDigitOf(String token) {
for (char ch : token.toCharArray()) {
if (ch >= '1' && ch <= '9') {
return ch - '0';
}
}
return 0;
}```
I sent that over to my teacher but he told me to try to use it without char or token. In particular I am having trouble finding an alternative to this phrase.
Java Code:
`for (char ch : token.toCharArray()) {`
Any alternative code to this?

7. Senior Member
Join Date
Jan 2013
Location
United States
Posts
2,722
Rep Power
4

## Re: Code to sort the leading digit of a number.

Since you are returning 0 if you can't find non-zero, you just want the first digit regardless. Try looking at the String methods. There are several that can do the job.

Regards,
Jim

8. ## Re: Code to sort the leading digit of a number.

my teacher but he told me to try to use it without char or token.
Is your teacher asking you to use int values? Not String or char.

A way to strip digits out of an int value is to use the % and / operators.

9. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

We haven't touched char at all in class, I just did some research and used it in self projects so I get it. We have touched on String I just don't know a way to put
for (char ch : token.toCharArray()) {
into a string compatible form.

10. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

Okay I think I came up with an alternative I am still stuck on the math.abs(i); error. I didnt post all the code which is my bad but changing the int [] to just int creates other problems posed earlier in the code.
Here is the ENTIRE code.
Java Code:
```import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BenfordsLaw {

public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("input file name? ");
String name = console.nextLine();
Scanner input = new Scanner(new File(name));
int[] count = countDigits(input);
reportResults(count);
}

// Reads integers from input, computing an array of counts
// for the occurrences of each leading digit (0-9).
public static int[] countDigits(Scanner input) {
int[] count = new int[10];
int i = input.nextInt();
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
}

// returns the first nonzero digit of a string, 0 if no such digit found
public static int firstDigitOf(String digits) {
if (digits.length() == 0)
return 0;
int firstDigit = Integer.parseInt(digits.substring(0, 1));
if (firstDigit > 0 && firstDigit < 10)
return firstDigit;
return  firstDigitOf(digits.substring(1));
}

// Reports percentages for each leading digit, excluding zeros
public static void reportResults(int[] count) {
System.out.println();
if (count[0] > 0) {
System.out.println("excluding " + count[0] + " tokens");
}
int total = sum(count) - count[0];
System.out.println("Digit Count Percent");
for (int i = 1; i < count.length; i++) {
double pct = count[i] * 100.0 / total;
System.out.printf("%5d %5d %6.2f\n", i, count[i], pct);
}
System.out.printf("Total %5d %6.2f\n", total, 100.0);
}

// returns the sum of the integers in the given array
public static int sum(int[] data) {
int sum = 0;
for (int n : data) {
sum += n;
}
return sum;
}

// returns the first digit of the given number
public static int firstDigit(int n) {
int result = Math.abs(n);
while (result >= 10) {
result = result / 10;
}
return result;
}
}```
How should I change this code to eliminate the Type mismatch error but not coming up with any other errors.

11. ## Re: Code to sort the leading digit of a number.

the Type mismatch error
Please copy the full text of the error messages for the posted code and paste it here. It has important info about the error.

12. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to int[]

at BenfordsLaw.countDigits(BenfordsLaw.java:27)
at BenfordsLaw.main(BenfordsLaw.java:15)

13. ## Re: Code to sort the leading digit of a number.

Type mismatch: cannot convert from int to int[]
at BenfordsLaw.countDigits(BenfordsLaw.java:27)
At line 27 the compiler found code that tries to convert an int to an int[]. That can't be done. See post#4

14. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

I know that but the problem is if I change the int [] to int on line 21 I get a error on line 15

15. Senior Member
Join Date
Jan 2013
Location
United States
Posts
2,722
Rep Power
4

## Re: Code to sort the leading digit of a number.

In the following code:
Java Code:
```// Reads integers from input, computing an array of counts
// for the occurrences of each leading digit (0-9).
public static int[] countDigits(Scanner input) {
int[] count = new int[10];
int i = input.nextInt();
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
}```
It is called countDigits but you aren't counting anything. Why do you have an array allocated? It isn't being used.
And why to you repeatedly take the absolute value of a number? No matter how many times you divide a number, it will never turn
negative.

I would recommend that you simply get the user input outside of the method and then use the method to get the first digit of the passed integer.

Regards,
Jim

16. ## Re: Code to sort the leading digit of a number.

I get a error on line 15
Change line 15 to be an int, not an int[]

17. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

The reportResults doesn't work on line 16

18. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

Nevermind the reportResults is pointless actually (i think), starting to get overwhelmed with the code.

19. ## Re: Code to sort the leading digit of a number.

Then go the other way: create an int[] and return that instead of an int value.

20. Member
Join Date
Nov 2013
Posts
22
Rep Power
0

## Re: Code to sort the leading digit of a number.

I had a friend recommend coding the first two sections like this:

Java Code:
```public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("input file name? ");
String name = console.nextLine();
Scanner input = new Scanner(new File(name));
int[] count = countDigits(input);
reportResults(count);

}

// Reads integers from input, computing an array of counts
// for the occurrences of each leading digit (0-9).
// Reads integers from input, computing an array of counts
// for the occurrences of each leading digit (0-9).
public static int[] countDigits(Scanner input) {
int[] count = new int[10];
while (input.hasNextInt()) {
int n = input.nextInt();
count[firstDigit(n)]++;
}
return count;
}```
I am wondering does "firstDigit" obtain the first digit of the number (could be a dumb questions sorry). If that is the case I am sure that is not allowed.

Page 1 of 2 12 Last

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•