我已經在下面發佈了我的代碼。我在聲明數組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