从方法返回的数组包含不需要的值。我不知道为什么。
这是DriverExam类:
public class DriverExam
{
private char[] answer = {'B','D','A','A','C','A','B','A','C','D',
'B','C','D','A','D','C','C','B','D','A'};
private char[] stuAnswer = new char[20];
private int totalCorrect = 0;
private int[] missed = new int[20];
public DriverExam(char stuAnswer[])
{
for (int i = 0; i < stuAnswer.length; i++)
{
this.stuAnswer[i] = stuAnswer[i];
}
}
public int gettotalCorrect()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] == answer[i])
totalCorrect++;
}
return totalCorrect;
}
public int gettotalIncorrect()
{
return 20-totalCorrect;
}
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
return missed;
}
}
这是主程序:
import java.util.Scanner;
public class Main6
{
public static void main(String[] args)
{
char[] answer = new char[20];
int[] missed2;
String str;
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= 20; i++)
{
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
while (Character.toUpperCase(str.charAt(0)) != 'A'
&& Character.toUpperCase(str.charAt(0)) != 'B'
&& Character.toUpperCase(str.charAt(0)) != 'C'
&& Character.toUpperCase(str.charAt(0)) != 'D')
{
System.out.println("Your input is invalid. Only accept A, B, C, or D");
System.out.println("Enter the answer for question #"+i);
str = keyboard.nextLine();
}
answer[i-1] = Character.toUpperCase(str.charAt(0));
}
DriverExam de = new DriverExam (answer);
System.out.print("***FINAL RESULT:");
System.out.print("\nTotal correct answers: "+de.gettotalCorrect());
System.out.print("\nTotal incorrect answers: "+de.gettotalIncorrect());
System.out.print("\nQuestions missed: ");
missed2 = de.getMissed();
for (int i = 0; i < missed.length; i++)
{
System.out.print(i+" ");
}
}
}
在DriverExam类中,我返回一个名为&#34;错过&#34;的数组。到主程序。在主程序中,我使用一个名为&#34; miss2&#34;存储返回的数组。但是当我打印结果时(我用&#34键入所有答案; A&#34;)。它如下所示:
最终结果:
总答错:6
总答错:14
错过的问题:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
错过结果的问题很奇怪且不正确。
答案 0 :(得分:0)
你想要“错过”的是一个可变长度的结果。要使用数组执行此操作,您将需要一个表示结果结束的值。在这里,我使用了-1。
public int[] getMissed()
{
int k = 0;
for (int i = 0; i < stuAnswer.length; i++)
{
if (stuAnswer[i] != answer[i])
{
missed[k] = i;
k++;
}
}
if(k < missed.length)
{
missed[k] = -1
}
return missed;
}
然后,在for循环中,检查结束值。奇怪的值可能是由于未在数组中明确设置它们而导致的默认int值。
for (int i = 0; i < missed2.length && missed2[i] != -1; i++)
{
System.out.print(i+" ");
}