我对此有很多疑问:
1)我想将Scanner放在哪个类下,以便它分配适当的变量?我得到的任务是说在Tester班级“将数据文件读入学生”
2)如何在“学生”课程中使用readFile()
方法?
3)如何在学生班和学生班上正确编写toString()
?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws IOException
{
//new Students object
Students theStudents = new Students();
//reads file from Students
theStudents.readFile();
// create new 'Output.txt' file to save program output
PrintWriter ot = new PrintWriter(new FileWriter("Output.txt"));
System.out.println(theStudents.toString());
ot.println(theStudents.toString());
ot.close();
}
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.io.FileReader;
public class Students
{
// instance variables
private ArrayList<Student> students;
public Students()
{
//create arraylist for students
students = new ArrayList<>();
}
public void readFile() throws IOException
{
String name;
int age;
double gpa;
String line;
//Scanner to read file
try {
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine()) {
name = sc.nextLine();
line = sc.nextLine();
age = Integer.parseInt(line);
line = sc.nextLine();
gpa = Double.parseDouble(line);
}
}
catch (FileNotFoundException e) {
System.out.println("Error");
}
}
public void add(Student s)
{
students.add(s);
}
public Students aboveAverage(double avgGPA)
{
Students aboveAverage = new Students();
for (int i = 0; i < students.size(); ++i) {
if (students.get(i).getGPA() > avgGPA)
aboveAverage.add(students.get(i));
}
return aboveAverage;
}
public String toString()
{
String out = "";
int count = 0;
for (Student student : students){
out += students.toString() + " ";
++count;
}
return out;
}
}
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGPA)
{
name = studentName;
age = studentAge;
gpa = studentGPA;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return String.format("%10s", name) +
String.format("%5d", age) + String.format("%10.2f \n", gpa);
}
}
答案 0 :(得分:2)
我不会为您提供完整的解决方案,但这是解决此问题的一种方法。
readLine()
而不是nextLine()
add()
函数,以将其添加到ArrayList中。代码段:
try (Scanner sc = new Scanner(new File("Students.txt"))) {
while (sc.hasNextLine()) {
String name = sc.readLine();
int age = Integer.parseInt(sc.readLine());
double gpa = Double.parseDouble(sc.readLine());
/* Create A New Student Object & Add To List */
add(new Student(name, age, gpa));
}
} catch (FileNotFoundException e) {
System.out.println("Error");
}
此外,您需要@Override
toString()
函数。