读取文件的最后一个条目时出错

时间:2016-02-25 22:41:26

标签: java java.util.scanner

我正在使用带扫描仪的分隔符读取文件。当我到达文件的最后一个条目时,它说我不在界外。如果我算得正确,我就会陷入困境。

这是代码,它抛出输入不匹配错误。任何帮助表示赞赏。感谢。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws IOException {
        String personName = null;
        double score = 0;

        File myFile = new File("twogrades.dat");

        try {
            Scanner scan = new Scanner(myFile).useDelimiter(",");

            while (scan.hasNext()) {
                personName = scan.next();

                for (int i = 0; i <= 5; i++) {
                    score += ((scan.nextDouble() / 50) * 0.03);
                }

                for (int i = 6; i <= 11; i++) {
                    score += ((scan.nextDouble() / 10) * 0.02);
                }
                score += ((scan.nextDouble()) * 0.20);
                score += ((scan.nextDouble()) * 0.50);

                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new FileWriter("grades.dat", true)));
                out.println(personName + " " + score);

                out.close();
                score = 0;
                scan.nextLine();
            }

            scan.close();
        } catch (InputMismatchException e) {
            System.out.println(e.getMessage()
                    + " You entered a wrong data type");
        } catch (NoSuchElementException e) {
            System.out.println(e.getMessage()
                    + " There are no more elements left in the file");
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
    }
}

这是文件

Yuri Allen,5,26,16,22,18,3,0,4,4,2,10,2,54,89

2 个答案:

答案 0 :(得分:1)

我能够重现错误,但前提是输入文件中有多行。问题是分隔符。您只能使用逗号","。因此,扫描程序尝试使用行的最后一个条目读取新行字符:"89\n"。由于这不是有效的双重,因此您将获得例外。

您可以通过将新换行符添加为分隔符来解决此问题:",|\\r\\n|\\r|\\n"

答案 1 :(得分:0)

我运行它,结果是:No line found There are no more elements left in the file和输出Yuri Allen 55.398。您可以清理,重建项目并进行更改:

while (scan.hasNext()) {

到这个

while (scan.hasNextLine()) {
相关问题