gpt4 book ai didi

java - 读取作为字符输入的文件时出现问题

转载 作者:行者123 更新时间:2023-12-01 15:41:34 26 4
gpt4 key购买 nike

我正在尝试为一个类创建一个构造函数,该类接受两个文件参数,并将文件中的信息放入我的数组字段中

我的程序代码如下所示:

 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();


}

唯一的问题是我无法一次读取一个字符。答案和关键如下:A乙

等等。

我已经在这里阅读了有关使用 FileInputStream 的内容,但我们在研究中尚未涉及到这一点。我收到有关无法将字符串读取为字符的错误。那我该怎么办呢?另外,我想没有办法将字符串转换为字符吗?

最佳答案

您可以尝试此 answerKey[i] = readKey.next().charAt(0) 并进行必要的边界/空检查。

关于java - 读取作为字符输入的文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com