我正在尝试为一个类创建一个构造函数,该类接受两个参数作为文件,并将信息放在我的数组字段中的文件中
我的程序代码如下所示:
import java.util.Scanner;
import java.io.*;
public class Chapter7ALabDemo
{
public static void main (String [] args) throws IOException
{
File file;
Scanner readKey;
Scanner readAnswers;
String str;
int numQuestions;
DriverExam student;
int [] missedQuestions;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the file that is the test key ");
str = keyboard.nextLine();
file = new File(str);
readKey = new Scanner(file);
System.out.println("Enter the name of the file with the student answers.");
str = keyboard.nextLine();
file = new File(str);
readAnswers = new Scanner(file);
System.out.println("How many test questions are there?");
numQuestions = keyboard.nextInt();
student = new DriverExam(readKey, readAnswers, numQuestions);
missedQuestions = student.questionsMissed();
System.out.println(student);
if (student.passed())
System.out.println("The student passed.");
else
System.out.println("The student did not pass.");
System.out.println("The student got " + student.totalCorrect() + " answers correct.");
System.out.println("The student got " + student.totalIncorrect() + " answers incorrect.");
System.out.println("The following questions were missed by the student: ");
student.printMissed(missedQuestions);
}
}
我的构造函数应该将数组实例化为给定大小,并将从文件读取的数据存储到应答键数组中,并将从另一个文件读取的数据存储到学生答案数组中。 我尝试的类中的构造函数看起来像这样注意:我只做了第一个显示的内容)
import java.util.Scanner;
public class DriverExam
{
private static char[] answerKey;
private static char[] studentAns;
public DriverExam(Scanner readKey,Scanner readAnswers,int numQuestions)
{
answerKey = new char[numQuestions];
for (int i = 0; readKey.hasNext() && i < numQuestions; i++)
answerKey[i] = readKey.nextChar();
}
唯一的问题是我一次无法阅读角色。答案和关键看起来像这样: 一个 乙 乙
等等。
我已经在这里阅读了关于使用FileInputStream的内容,但我们在研究中没有这样做。我得到一个关于无法读取字符串作为char的错误。那假设要做什么?另外,我认为没有办法将字符串转换为字符?
答案 0 :(得分:1)
您可以使用必要的边界/空值检查来尝试此answerKey[i] = readKey.next().charAt(0)
。