0

我想到了。我将计数器作为整数而不是双精度数。

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)它就变成了零。我做错了什么?

4

2 回答 2

0

您应该改用hasNextLineandnextLine方法。我认为,由于每个条目都在单独的行中,因此更有意义。

于 2012-10-14T21:57:23.863 回答
0

这似乎有效(打印 3):

public static void main(String[] args) throws Exception {
    File fileName = new File("test2.txt");
    Scanner inFile = new Scanner(fileName);
    int counter = 0;

    while (inFile.hasNext()) {
        String token = inFile.next();
        System.out.println(token);
        if (token.equals("GG")) {
            counter++;
        }
    }
    System.out.println(counter);
}
于 2012-10-14T21:57:39.667 回答