简体   繁体   English

如何在Java中存储文本文件中的令牌

[英]How to store tokens from a text file in java

I figured it out. 我想到了。 I had the counter's as integers instead of doubles. 我的计数器不是整数,而是整数。

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();
    }
}

I got everything to counter correctly, but when I do the math of (counterGG / totalCounter) and (counterBG / totalCounter) and (counterBB / totalCounter) it just comes out to zero. 我可以正确地进行所有计数,但是当我执行(counterGG / totalCounter)(counterBG / totalCounter)(counterBB / totalCounter)的数学运算时,结果只是零。 What have I done incorrectly? 我做错了什么?

You should use hasNextLine and nextLine methods instead. 您应该改为使用hasNextLinenextLine方法。 Since every entry is in a separate line it more sense, I think. 我认为,由于每个条目都在单独的一行中,因此更有意义。

This seems to work (prints 3): 这似乎可行(打印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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM