我正在编写一个程序来显示列表多项选择问题。我的 java 类的 ChoiceString 数据成员中存储的值有问题。类的每个实例都应该有自己的 ChoiceString 值,但由于某种原因,ChoiceString 只保存第一个实例初始化的值并与其他实例共享,我希望每个实例都有自己的 ChoiceString 唯一值。我该如何解决?
以下是我的代码:
public class AllChoiceQuestion extends ChoiceQuestion{
private String note = "Note: The following question has one or more correct choices\nYou must give the number(s) of ALL correct anwers, in order,\nto get full credit andsperated by spaces";
private int count =0;
// A varabile that will hold the user answer
private String choiceString;
public AllChoiceQuestion(String questionText) {
// initilize the question text value
super(questionText);
choiceString="";
}
public void addChoice(String choice, boolean correct){
super.addChoice(choice, correct);
if(correct == true){
count++;
choiceString += "" + count+" " ;
}
super.setAnswer(choiceString.trim());
}
public void display(){
System.out.println(note);
super.display();
}
public String toString(){
return note +"\n"+ super.toString();
}
}
这是我的实例的代码
ChoiceQuestion allchoicequestion1 = new AllChoiceQuestion("Which of the basic data type(s) has the size of 16 bit?");
allchoicequestion1.addChoice("Char", true);
allchoicequestion1.addChoice("Short", true);
allchoicequestion1.addChoice("Float", false);
allchoicequestion1.addChoice("Double", false);
ChoiceQuestion allchoicequestion2 = new AllChoiceQuestion("Which of the basic data type(s) has the size of 64 bit?");
allchoicequestion2.addChoice("Long", false);
allchoicequestion2.addChoice("Doulbe", false);
allchoicequestion2.addChoice("Byte", true);
allchoicequestion2.addChoice("Int", true);
所以 allChoiceQuestion1 的 ChoiceStrng 应该是 1 2 而 ChoiceString forallChoiceQuestion2 应该是 3 4 但每次我 tyee 3 4 作为 forallChoiceQuestion2 的答案时,它都会给我一个错误的答案,但如果我输入 1 2 它是正确的