JAVAutil。扫描仪在Java中将文本文件加载到对象中
我试图写一个类,但遇到了问题。我遇到的问题是,我需要读入一个文本文件,然后将其从方法中返回。我犯了很多错误。有人能帮我吗
文本文件如下所示
问题1
答复1
问题2
答复2
问题3
答复3
等等
import java.io.*;
import java.util.*;
public class Quiz {
private String fName; // Name of the file you will be reading from
private Scanner theFile; // Scanner use to read from the file
public int status = 0;
public String line = null;
public int i = 0;
// Create a new Quiz object by opening the associated file. Note that this
// method throws an IOException, so in the method that calls it you must
// also
// have in the header "throws IOException". We will discuss how to handle
// these exceptions later.
public Quiz(String f) throws IOException {
File Quiz = new File(f);
Scanner theFile = new Scanner(Quiz);
theFile.close();
return Quiz;
}
// First check the status. If it is 1 or 2 simply return false.
// If it is 0, check the file:
// If there is a line in the file, return true
// If there is no line in the file, set status to 1 and
// return false.
public boolean hasAQuestion() {
if (status == 1 || status == 2) {
return false;
}
else if (status == 0) {
if (line = theFile.readLine() != null) {
return true;
}
else if (line = theFile.readLine() == null) {
status = 1;
return false;
}
}
}
// Return that status of the Quiz object:
// Status = 0: everything ok
// Status = 1: end of file reached
// Status = 2: error has occurred
public int getStatus() {
if (line = theFile.readLine() != null) {
status = 0;
}
else if (line = theFile.readLine() == null) {
status = 1;
}
else if (line.theFile.readLine() == " ") {
status = 2;
}
return status;
}
// Get the next question and set the status appropriately:
// If status is not 0, return null, otherwise:
// If no lines are left before anything is read, set status
// to 1 and return null
// If the question is read but no answer left, set status to
// to 2 and return null
// If both the question and answer are read, return them in
// a new Question object.
public Question getQuestion() {
return null;
}
}
# 1 楼答案
您试图从构造函数返回一个对象,但您不能这样做
另外,
theFile.readLine()
-Scanner
没有readLine()方法,只有nextLine()
# 2 楼答案
那么首先,
这不是一个好的做法
Quiz
是类的名称File
也是类的名称。如果要创建文件对象,请执行以下操作:您不应该希望在测验构造函数中创建测验对象,因为构造函数将调用测验构造函数。。。你会陷入一个无限循环。这可能只是一个命名错误,但请记住不要以大写字母开头变量名,还要避免在测验类中进行文件对象名测验,因为这会导致一些混淆
因此,无论如何,您的错误来自这一行:
您刚才所做的是创建了一个Scanner对象,打开一个流从文本文件中读取,然后关闭它。因此,现在您不可能读取该文件,因为您刚刚关闭了流。解决这个问题的方法是在quick类中有一个
close()
方法,当它从文件中读取完后,其他类将调用该方法最后,
构造函数不返回任何内容。它们只是构造类的一个对象。另外,我也不完全确定,但您可能会混淆类和对象是什么。类就像对象的模板;对象可以做的事情以及它具有的属性是由类定义的。例如,在声明中
您正在创建Cat类的对象(bob)
语句
return Quiz;
,即使它不在构造函数中,也没有任何意义,因为您返回的是类而不是对象。如果您想要一个静态方法返回一个对象,那么它应该是不是 返回猫