1

我正在编写一个程序来显示列表多项选择问题。我的 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 它是正确的

4

3 回答 3

0

correct问题是当变量为假时你没有增加计数。因此,选择字符串将始终为 1 2。

于 2012-05-27T07:15:49.357 回答
0

每次在构造函数中都将choiceString 初始化为“”。

尝试

choiceString = questionText;
于 2012-05-27T06:51:07.567 回答
0

您需要扩展AllChoiceQuestion并拥有它的子类,NumberChoiceQuestion并且StringChoicQuestion它们将有自己的实现choiceString,您需要choiceString在子类中重载实现并创建子类的对象,这样您就可以让您的子类特定choiceString


 public class NumberChoiceQuestion extends AllChoiceQuestion{
        this.choiceString; // Over written value of choiceString specific to NumberChoiceQuestion
    }

public class StringChoiceQuestion extends AllChoiceQuestion{
        this.choiceString; // Over written value of choiceString specific to StringChoiceQuestion
    }
于 2012-05-27T06:52:07.263 回答