0

私はそれを考え出した。カウンターは double ではなく整数でした。

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)ゼロになります。私は間違って何をしましたか?(counterBG / totalCounter)(counterBB / totalCounter)

4

2 に答える 2

0

hasNextLine代わりにandnextLineメソッドを使用する必要があります。すべてのエントリが別の行にあるので、より意味があると思います。

于 2012-10-14T21:57:23.863 に答える
0

これはうまくいくようです(prints 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 に答える