I'm trying to find the occurrence of each number in pi (how many 1's, 2's, 3's are there). I've got the number of occurrences for each digit working, but when I try to find the percent of each number, I always get 0. Here's the code:
import java.util.*;
import java.io.*;
import java.net.*;
import java.text.DecimalFormat;
public class PIAnalyzer {
static int digit, index;
public static Scanner openFileURL(String website) {
Scanner scan = null;
try {
URL webAddress = new URL(website);
InputStream input = webAddress.openStream();
System.out.println("Opened web page: " + webAddress.getPath());
scan = new Scanner(input);
} catch (MalformedURLException e) {
System.out.println("Cannot open web site:");
System.out.println(e);
} catch (IOException io) {
System.out.println("IO Error:" + io.toString());
}
return scan;
}
public static void main(String[] args) {
//System.getProperties().put("http.proxyHost", "10.10.1.5");
//System.getProperties().put("http.proxyPort", "8080");
DecimalFormat df = new DecimalFormat("#.##");
int[] digitCount = new int[10];
Scanner in = openFileURL("http://www.eveandersson.com/pi/digits/1000000");
if (in == null) {
System.out.println("URL error");
}
//ignore web page fluff at the beginning; adjust the loop so this works.
//we are displaying the lines of text to make it easier to determine if we are ignoring the correct amount.
for (int i = 0; i < 20; i++) {
System.out.println(in.nextLine());
}
String line;
char ch;
int index;
//We analyze the file line by line
int countChars = 0;
while (in.hasNext() && countChars < 1000) {
line = in.nextLine();
countChars += line.length();
System.out.println(line);
char[] pear = line.toCharArray();
//to look at each character, use charAt or toCharArray
// look at each character.
//for loop through the string.
for (int i = 0; i < pear.length; i++) {
ch = pear[i];
if (Character.isDigit(ch)) {
index = ch - '0';
digitCount[index]++;
}
}
} //end while loop through lines
//get sum of all numbers in for loop
int sum = 0;
for (int a = 0; a <= digitCount.length - 1; a++) {
sum += digitCount[a];
}
System.out.println("Number of total char: " + countChars);
System.out.println("Number of char proccessed: " +sum + " //why?");
System.out.println("Digit" + "\t" + "# occurrence" + "\t" + "% occurrence");
for (int i = 0; i <= digitCount.length - 1; i++) {
System.out.print(i + "\t" + digitCount[i]);
int percentOccurence = ((digitCount[i] / sum));
System.out.println("\t\t" + percentOccurence + "%");
}
}
}