Saturday, November 30, 2013

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 file called data.txt - you can put any data you want in the file, such as US population numbers over the past 100 years, etc. Just make sure all of the data is of type integer! This file 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.































No comments:

Post a Comment