我已经在下面发布了我的代码。我在声明数组wrongAnswers的行有一个问题。我以前能够让我的代码工作,但问题是有些人自己删除了我的所有文件。我能够在不使用List
或ArrayList
的情况下工作。我只想了解,在尝试使用其他方法之前,我现在可以如何开始工作。我明白Java数组是不可变的。不过,我仍然可以在以前的某个方面做到这一点。如果有人能帮我弄清楚我以前做过什么,我会非常感激。数组大小声明
private Scanner keyboard = new Scanner(System.in);
private final String[] testAnswers = {
"B","D","A","A","C",
"A","B","A","C","D",
"B","C","D","A","D",
"C","C","B","D","A"};
private String[] studentAnswers = new String[20];
/*
private String[] studentAnswers = {
"B","D","A","A","C",
"A","B","A","C","D",
"B","C","D","A","D",
"C","C","B","D","A"};
*/
private int[] wrongAnswers;
private int answeredCorrectly = 0;
public void getStudentAnswers() {
for(int x = 0; x < 20; x++) {
do {
System.out.print("Enter answer for #" + (x + 1) + " : ");
this.studentAnswers[x] = keyboard.next().toUpperCase();
if (!"A".equals(this.studentAnswers[x]) &&
!"B".equals(this.studentAnswers[x]) &&
!"C".equals(this.studentAnswers[x]) &&
!"D".equals(this.studentAnswers[x])) {
System.out.println("Invalid input.");
}
} while(!"A".equals(this.studentAnswers[x]) &&
!"B".equals(this.studentAnswers[x]) &&
!"C".equals(this.studentAnswers[x]) &&
!"D".equals(this.studentAnswers[x]));
}
}
public int totalCorrect() {
int arrayLocation = 0;
for(int x = 0; x < 20; x++) {
if (this.studentAnswers[x].equals(this.testAnswers[x]))
this.answeredCorrectly++;
else
this.wrongAnswers[arrayLocation++] = x;
}
return this.answeredCorrectly;
}
public int totalIncorrect() {
return 20 - this.answeredCorrectly;
}
public boolean passed() {
return this.answeredCorrectly >= 15;
}
public void questionsMissed() {
if(this.answeredCorrectly != 20) {
for(int x = 0; x < this.wrongAnswers.length; x++) {
System.out.println(this.wrongAnswers[x]);
}
}
}
'wrongAnswers = new int [someNumber];'但是我认为使用List会更好 – litelite
我不能这样做,因为wrongAnswers的数组大小取决于给出多少正确答案。每次我运行程序时它都会改变。该数字需要灵活 –
要么你需要手动创建一个新的更大的每一次,并复制旧的+每当你想添加一个新的错误答案。或者使用'ArrayList' – litelite