0
我試圖找到pi中每個數字的出現次數(有多少個1,2,3在那裏)。我有發生的每一位工作的數量,但是當我試圖找到每個數字的百分比,我總是得到0下面的代碼:查找百分比總是等於0?
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 + "%");
}
}
}
啊確定。我改變了int percentOccurence =((digitCount [i]/sum));加倍百分比=((digitCount [i] /(double)sum)* 100);現在它完美地工作。謝謝! – 2015-03-13 12:04:09