2

我正在努力解决一个特定问题,但鉴于这在技术上是家庭作业,我想了解我做错了什么,我希望有一个更通用的解决方案。一些警告:我必须使用扫描仪类,并且我的数据不在数组或任何东西中。我从网站上的阅读中知道 BufferedReading 是首选。从我读过的内容来看,我想我也更喜欢它。但这不是我可以在这里工作的。

我正在尝试从数据文件中读取数据,然后对该文件执行一些操作。数据是这样的:

1234 55 64 75
1235 44 32 12
...
nnnn xx yy zz
0
2234 47 57 67
2235 67 67 67
...
nnnn xx yy zz
0

每行是一个 ID,后跟三个等级。每个类都以零线终止,然后 while 循环从顶部开始:

while (classContinues == true) {                   
//get the student's data and assign it in the program
studentID = inputFile.nextInt();
programGrade = inputFile.nextInt();
midtermGrade = inputFile.nextInt();
finalGrade = inputFile.nextInt();

// in here I'm doing other stuff but I don't need help with that

// check if the class has more students
if (inputFile.nextInt() == 0) {
    classContinues = false;
} else {
    classContinues = true;
    inputFile.nextLine(); // eat the rest of the line
}
}

现在,当你像这样运行代码时,它会打印出我想要的输出,但它会跳过每隔一行的数据。删除 inputFile.nextLine(); 它会跳过第二个学生 ID,然后弄乱所有其他输出。所以我想我想知道我做错了什么——我应该如何在不吃下一个学生证的情况下检查下一个整数是否为零?

4

2 回答 2

1

当涉及到输入的第一个 '0' 时,下面的代码将跳出 while 循环。这就是它无法捕获所有记录的原因。

if (inputFile.nextInt() == 0) {
    classContinues = false;
} else {
    classContinues = true;
    inputFile.nextLine(); // eat the rest of the line
}

而对于 nextInt() 方法,当它被调用时,它会返回当前的 int 值并指向下一个。

试试下面的while代码,它可以得到每一行的成绩记录。我创建了一个名为 StudentGrade 的实体来存储记录。For each 循环将打印出存储在列表中的记录。

    while (classContinues == true) {
        StudentGrade stu = new StudentGrade();
        // get the student's data and assign it in the program
        int id = 0;

        if ((id = inputFile.nextInt()) != 0) {
            stu.studentID = id;
        stu.programGrade = inputFile.nextInt();
        stu.midtermGrade = inputFile.nextInt();
        stu.finalGrade = inputFile.nextInt();
        studentGrades.add(stu);
        // in here I'm doing other stuff but I don't need help with that
        // check if the class has more students
        }
        else if (!inputFile.hasNext()) {
            classContinues = false;
        }
    }

    for (StudentGrade s : studentGrades) {
        System.out.println(s);
    }

输入数据:

1234 55 64 75
1235 44 32 12
1236 23 32 32
0
2234 47 57 67
2235 67 67 67
2236 23 23 2
0

输出:

1234 55 64 75
1235 44 32 12
1236 23 32 32
2234 47 57 67
2235 67 67 67
2236 23 23 2

顺便说一句,最好使用 Mehmet 的方法来获取记录,这样更容易理解。

PS 这是我在 StackOverflow 中的第一个答案。希望它可以提供帮助。

于 2013-10-21T08:36:28.953 回答
0

将每一行存储到一个字符串变量中,从该行解析整数,然后通过从该字符串读取它来分配它们,而不是从该行本身。所以:

String nextLine;

while (classContinues)
{             
nextLine = inputFile.nextLine();

String[] tokens = nextLine.split(" ");

if(tokens.length == 1) //this means line has '0' character
    classContinues = false;
else
    {
    classContinues = true;

    studentID = tokens[0];
    programGrade = tokens[1];
    midtermGrade = tokens[2];
    finalGrade = tokens[3];

    // your stuff
    }
}

如果有任何类型的错误会显示此代码的误导性结果,那可能是我的错,因为我不了解项目的其余部分。所以我发布了一个类似于你的代码。

此外,您必须对从 nextLine 方法获得的字符串进行空检查。

于 2013-10-21T06:05:26.993 回答