我想到了。我将计数器作为整数而不是双精度数。
public class Family
{
public static void main(String[] args) throws IOException
{
String token = "";
File fileName = new File("MaleFemaleInFamily.txt");
Scanner inFile = new Scanner(fileName);
double counterGG = 0;
double counterBG = 0;
double counterBB = 0;
double totalCounter = 0;
while (inFile.hasNext())
{
token = inFile.next();
System.out.println(token);
if (token.equals("GG")) {
counterGG++;
totalCounter++;
} else if (token.equals("BG")) {
counterBG++;
totalCounter++;
} else if (token.equals("GB")) {
counterBG++;
totalCounter++;
} else if (token.equals("BB")) {
counterBB++;
totalCounter++;
}
}
System.out.println();
System.out.println("Sample Size: " + totalCounter);
System.out.println("Two Boys: " + (counterBB / totalCounter) + "%");
System.out.println("One Boy One Girl: " + (counterBG / totalCounter) + "%");
System.out.println("Two Girls: " + (counterGG / totalCounter) + "%");
inFile.close();
}
}
我得到了正确反击的一切,但是当我计算(counterGG / totalCounter)
and时(counterBG / totalCounter)
,(counterBB / totalCounter)
它就变成了零。我做错了什么?