我今天早些时候曾就此计划提出过问题,并且能够获得我需要完成的大部分工作,但似乎人们不再关注它了 Here's指向它的链接。
以下是我现在所拥有的:
import java.util.*;
import java.text.*;
public class Lab4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
int students;
int correctAnswers=0;
char [] answerKey= { 'B' , 'D' , 'A' , 'A' , 'C' , 'A' , 'B' , 'A' , 'C' , 'D' , 'B' , 'A' };
char [] userAnswers = new char[answerKey.length];
DecimalFormat df = new DecimalFormat("#0.0");
System.out.print("how many students are in your class?");
input = s.nextLine();
students=Integer.parseInt(input);
String [] name = new String[students];
int j=1;
while(students>=j)
{
System.out.print("Enter name of student" + j + ": ");
name[j] = s.nextLine();
System.out.print("Enter quiz score answers");
userAnswers[answerKey.length] = s.next().charAt(0);
for (int i = 0; i < userAnswers.length; ++i)
{
if(userAnswers[i]==answerKey[i]);
correctAnswers++;
}
System.out.print((df.format(correctAnswers/answerKey.length)) + "%");
j++;
}
}
}
但是在我输入用户的答案后,我一直收到这个错误:
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException: 12在Lab4.main(Lab4.java:29)
我不确定这意味着什么或如何解决它。
答案 0 :(得分:3)
这意味着您的数组索引可能超过数组中的元素数。从您的代码中,您似乎展示了Off-by-one error。请注意,Java数组基于零,即数组索引从0开始,以array.length - 1
结束。
(注意:未经测试的代码,我几个月没有使用Scanner
...)
更改
int j=1;
while(students>=j)
到
int j = 0;
while (students > j)
而且,这条线
userAnswers[answerKey.length] = s.next().charAt(0);
这是一个逻辑错误。根据@Creakazoid的答案,不只是写出界限,即使它被修复了,你将把所有答案都写到数组的最后一个元素,这意味着你将所有学生的答案都作为用户的最后一个字符输入
这应该是
for (int i = 0; i < answerKey.length; ++i) {
userAnswers[i] = s.next().charAt(0);
}
编辑:看起来您需要阅读一系列完整答案的输入。因此,读取整行,然后将行分为字符。 (另)
String line = s.nextLine();
for (int i = 0; i < answerKey.length; ++i) {
userAnswers[i] = line.charAt(i);
}
此外,
if(userAnswers[i]==answerKey[i]);
注意到行尾的分号?你正在写一个空语句(由一个分号组成),correctAnswers++;
无论这个条件是否为真都会运行
将其更改为
if (userAnswers[i] == answerKey[i])
您可能需要更改
System.out.print("Enter name of student" + j + ": ");
到
System.out.print("Enter name of student" + (j + 1) + ": ");
这样输出不受影响,但
实际上,你的while循环可以用for循环替换 - 它更容易阅读:
for (int j = 0; j < students; ++j) {
// .. your code
}
答案 1 :(得分:0)
userAnswers[answerKey.length] = s.next().charAt(0);
数组索引从零开始,因此最后一个可寻址索引为answerKey.length - 1
。