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

标签 java arrays file input char

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

我的程序代码如下所示:

 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/

相关文章:

java - 如何搜索对象中的数据并转换为列表

c - 如何解释这段代码 : if (strstr(line, *argv) != EOF) != except

c# - new[] 和 new string[] 有什么区别?

java - 如何将 java.io.File 转换或转换为 java.io.List?

c++ - 在 C++ 中打印带有扩展名的当前文件名

javascript - 输入类型 ='file' 接受 pdf 和 excel 文件扩展名

JAVA & SQL 数据库保存更改

java - C# 相当于 Java 的 KDFCounterBytesGenerator(来自 bouncycaSTLe)

java - 如何获取 SortedSet 的下一个元素?

c - 如何调用以指针数组作为参数的函数?在C中