【问题标题】:Having problems reading a files input as characters读取作为字符输入的文件时出现问题
【发布时间】:2011-12-19 02:32:03
【问题描述】:

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

我的程序代码如下所示:

 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 的信息,但在我们的研究中还没有涉及到。我收到关于无法将字符串读取为字符的错误。那么假设要做什么呢?另外,我认为没有办法将字符串转换为字符?

【问题讨论】:

  • 输入文件如下所示:
  • 输入文件如下所示:A\n B\n B\n

标签: java arrays file input char


【解决方案1】:

你可以试试这个answerKey[i] = readKey.next().charAt(0) 进行必要的边界/空检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    相关资源
    最近更新 更多