【发布时间】:2018-01-25 06:13:20
【问题描述】:
所以我试图将一个 txt 文件读入一个 char 数组并打印出内容,但我只得到了要打印的字符串的第一个索引。文件内容为“EADBC”
public static void main(String args[]) throws IOException
{
char [] correctAnswers = new char [20];
String [] studentName = new String[5];
char [][] studentAnswers = new char [20][20];
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Quiz Grading System \n");
System.out.println ("Please Enter the name of the file that contains the correct answers");
Scanner answerFile = new Scanner (new File (sc.next() + ".txt"));
int i = 0;
int fillLvl = 0;
String answer;
while (answerFile.hasNext() )
{
answer = answerFile.next();
correctAnswers[i] = answer.charAt(i);
i++;
fillLvl = i;
}
answerFile.close();
System.out.println("Correct Answers: ");
for(int j = 0; j < fillLvl; j++)
{
System.out.println(correctAnswers[j]);
}
【问题讨论】:
-
answerFile.next();将返回下一个 Token 是EADBC,所以如果这就是文件中的全部内容,那么它将不再循环。尝试阅读此字符串,然后将其拆分。尝试在调试器中运行它。 -
我尝试做类似的事情:字符串答案; while (answerFile.hasNext() ) { answer = answerFile.next(); for(int i = 0; i
-
... 和 ?会发生什么?
-
我只让它打印出 E D C,我没有将字符串中的每个索引都放入数组中
-
你增加了两次
i- 删除第二次i++