简体   繁体   English

使用扫描仪读取文本文件时出现问题

[英]Problems with reading a text file with scanner

I'm trying to read data from a text file, but I'm having trouble getting it to work. 我正在尝试从文本文件中读取数据,但无法使其正常工作。 This is what I have so far 这就是我到目前为止

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

    public class Student {
        private String firstName;
        private String lastName;
        private int homeworkScore;
        private int testScore;
        private String letterGrade;
        private int numberOfStudents;

        public Student() {

            numberOfStudents = 0;
            homeworkScore = 0;
            testScore = 0;

        }

        public static void main(String[] args) {

            Scanner scanner = null;
            try {
                scanner = new Scanner(new File("grades.txt"));
            } catch (FileNotFoundException e) {
                System.out
                        .println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
                System.exit(0);
            }
        }

        public void setNumberOfStudents() {
            Scanner scanner = new Scanner(System.in);
            numberOfStudents = scanner.nextInt();

        }

        public void setFirstName() {
            Scanner scanner = new Scanner(System.in);
            String firstName = scanner.next();
        }

        public void setLastName() {
            Scanner scanner = new Scanner(System.in);
            String lastName = scanner.next();
        }
    }

And this is the driver class I have so far: 这是我到目前为止拥有的驱动程序类:

public class CourseGrade {

    public static void main(String[] args) {
        Student myStudent = new Student();
        myStudent.setNumberOfStudents();
        myStudent.setFirstName();
        myStudent.setLastName();
    }

}

When I run the driver class, nothing happens, so I'm not sure if it's actually setting the values to what I want. 当我运行驱动程序类时,什么也没有发生,因此我不确定它是否实际上将值设置为所需的值。 I know the file is being read because I'm not getting the error message, but I'm not sure if the values are actually being set 我知道正在读取文件,因为我没有收到错误消息,但是我不确定是否实际设置了值

You aren't actually iterating through the file with your scanner. 您实际上并没有使用扫描仪遍历文件。 All you're doing is initializing the Scanner object with the file. 您要做的只是用文件初始化Scanner对象。

You'll need to do something like: 您需要执行以下操作:

 while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    //do stuff...
 }

As was pointed out in the comment section of your question, the Scanner is being initialized in your Student class main method - which seems wrong. 正如您的问题的注释部分所指出的那样, Scanner正在您的Student类main方法中初始化-似乎是错误的。 You could have a static method on Student that reads this file and constructs the Student object based on the data. 您可以在Student上有一个静态方法,该方法读取该文件并根据数据构造Student对象。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Student {
    private String firstName;
    private String lastName;
    private int homeworkScore;
    private int testScore;
    private String letterGrade;
    private int numberOfStudents;

    public Student() {

        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("grades.txt"));
        } catch (FileNotFoundException e) {
            System.out
                    .println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
            System.exit(0);
        }

        //Assumed file content is as expected
        this.numberOfStudents = scanner.nextInt();
        this.firstName = scanner.next();
        this.lastName = scanner.next();
    }
}

And following driver class will print the values set when calling constructor. 并且以下驱动程序类将在调用构造函数时打印设置的值。

public class CourseGrade {

  public static void main(String[] args) {

    Student myStudent = new Student();
    //Your requirement is done by now
  }

}

Ok, I got it to work, and this is what I did: 好的,我已经开始工作了,这就是我所做的:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Student {
    private String firstName;
    private String lastName;
    private int homeworkScore;
    private int testScore;
    private String letterGrade;
    private int numberOfStudents;
    Scanner scanner = null;
    {
        try {
            scanner = new Scanner(new File("grades.txt"));
        } catch (FileNotFoundException e) {
            System.out
                    .println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
            System.exit(0); // Error message is shown when file is not found
        }
    }

    public Student() {
        homeworkScore = 0;
        testScore = 0;
        numberOfStudents = 0;

    }

    public void setNumberOfStudents() {
        numberOfStudents = scanner.nextInt();

    }

    public int getNumberOfStudents() {
        return numberOfStudents;
    }

    public void setFirstName() {
        firstName = scanner.next();

    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName() {

        lastName = scanner.next();
    }

    public String getLastName() {
        return lastName;
    }

    public void setHomeworkScore() {

    }

    public int getHomeworkScore() {
        return homeworkScore;
    }

    public void setTestScore() {

    }

    public int getTestScore() {
        return testScore;
    }
}

And then when I run this new driver class: 然后,当我运行这个新的驱动程序类时:

public class CourseGrade {

    public static void main(String[] args) {
        Student myStudent = new Student();
        myStudent.setNumberOfStudents();
        myStudent.setFirstName();
        System.out.print(myStudent.getFirstName() + " ");
        myStudent.setLastName();
        System.out.print(myStudent.getLastName());

    }

}

It prints out the name of the first person in the text file! 它会打印出文本文件中第一个人的名字! I still have to set up the methods for computing test and homework score, but it seems to all be working now. 我仍然必须设置计算测验和家庭作业分数的方法,但是现在看来一切都在起作用。 Thanks for the help! 谢谢您的帮助!

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

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