我在学生班中创建了以下实例变量:
private String name;
private char gender; // 'M' / 'F'
private Date birthday;
private Preference pref;
private boolean matched;
为我创建的Preference类
private int quietTime; // scale of 1-10
private int music; // 1 - 10
private int reading; // 1 - 10
private int chatting; // 1 - 10
对于我创建的日期类
private int year; // between 1900 to 3000
private int month; // between 1 to 12, 1 is jan;
private int day; // between 1- 31 assume feb max is 28 days!
麻烦是我尝试导入以下库的主要方法
import java.util.Scanner;
import java.io.File;
我想读取txt文件并将每个数据存储到Student实例变量中,下面是我试过的代码,但是我收到了关于 “学生无法解决变量” 例如,下面是文本文件中的一行:
Abhay F 1-5-1994 0 0 0 0 // seperate by tab and '-'
我的匹配类代码 - 主要方法类:
`
Student[] students = new Student[100];
int bestScore = 0;
String readInfo = "";
Scanner inFile = new Scanner(new File("Students.txt")).useDelimiter("\t-");
for (int i = 0; i < 100; i++) {
readInfo = inFile.next();
student[i] = readInfo;
}
inFile.close();
}
}
while(1) {
r.nextBoolean();
if (!nextBoolean())
{
return true;
}
`
我刚刚开始学习java十天,我完全是一个新手,可能有人帮我修复错误,我真的很好看!!
答案 0 :(得分:1)
如果要读取或写入文件,可以使用这些流。它比Scanner好。
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("path\\to\\your\\file.txt")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path\\to\\your\\second\\file.txt")));
//read one line from your file
String line = reader.readLine();
//write something to your file
writer.write(line);
}
如果要将整个对象写入文件,Java具有ObjectInput / Output流。
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("yourFile.bin"))); //or any file type
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("yourFile.bin")));
output.writeObject(yourObject);
YourObject yourObject = input.readObject();
}
答案 1 :(得分:1)
您具体遇到的错误与您实例化一系列名称&#34;学生&#34;但是你引用了一个名字&#34; student&#34;的数组。
由于您从未实例化过学生数组,因此会出现以下错误:学生无法解析为变量。
尝试:
students[i] = readInfo;