简体   繁体   English

为什么不读取while语句?

[英]Why isn't while statement being read?

I have a .dat file with the following information: 我有一个.dat文件,其中包含以下信息:

Erik 3 Rita 7 Tanner 14 Jillyn 13 Curtis 4 Stephanie 12 Ben 6

It reads boy's name, boys age, girl's name , girl's age etc. 它读取男孩的名字,男孩的年龄,女孩的名字,女孩的年龄等。

I have to count the total number of boys and total number of girls, then add the ages of the boys and the ages of the girls, then find the difference between them (Absolute). 我必须计算男孩的总数和女孩的总数,然后将男孩的年龄和女孩的年龄相加,然后找出它们之间的差(绝对值)。

I have created the following code to do this: 我创建了以下代码来做到这一点:

public class Exercise1 {
public static void main(String[] args) 
    throws FileNotFoundException {
    Scanner input = new Scanner(new File(
            "C:/FilesForJava/ChapterSixExerciseOne.dat"));
    boyGirl(input);     
}
public static void boyGirl(Scanner fileInput) {
    int boysCount = 0, girlsCount = 0, counter = 1,
            boysSum = 0, girlsSum = 0;
    while(fileInput.hasNext()){         
        if(counter % 2 != 0) {
            boysCount++;
        }
        else {
            girlsCount++;
        }
        while(fileInput.hasNextInt()) {
            if(counter % 2 != 0) {
                boysSum += fileInput.nextInt();
            }
            else {
                girlsSum += fileInput.nextInt();;
            }           
        }
        counter++;
    }
    System.out.println(boysCount + "Boys, " + girlsCount + "Girls");
    System.out.println("Difference between boys' and girls' sums: " + Math.abs(boysSum - girlsSum));
}

The problem is that the program never enters the nested while statement and I can't figure out what I am doing wrong. 问题在于程序永远不会输入嵌套的while语句,而且我无法弄清楚自己在做什么错。 Not only does it always bypass it, the first while statement never ends so it perpetually loops. 它不仅总是绕过它,而且第一个while语句永远不会结束,因此它会永久循环。 The book uses .dat files in their examples. 本书在示例中使用.dat文件。 I used notepad to create the file and saved it as a .dat file. 我使用记事本创建文件并将其另存为.dat文件。 Could this be my problem? 这可能是我的问题吗?

Please advise. 请指教。

fileInput.hasNext() must be followed by next() , so that the token is consumed and the file moves forward. fileInput.hasNext()必须是next() ,以便使用令牌并向前移动文件。

Otherwise, the file position is always the begining, and there is always a next token ('Erik'), and never a next int. 否则,文件位置将始终是开头,并且始终存在下一个标记('Erik'),而永远不会有下一个int。

Typically, I would: 通常,我会:

while(fileInput.hasNext()){
    System.out.println("Kid's name: " + fileInput.next());
    // Rest of your code

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

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