总是得到“错误”

时间:2014-11-10 20:09:28

标签: java oop

我正在制作一个测验计划。第一步,我正在接受老师/用户的测验问题及其正确答案。我有一个名为TrueFalseQuestion的子类,它将布尔模型答案和字符串问题作为参数。我已经创建了一个TrueFalseQuestion类型的数组,并且我被困在这个部分,我运行代码,插入一个问题,无论我插入的模型答案是真还是假,当我打印时它始终存储为false出来。救命? 这是我的代码的这一部分:

   System.out.println("How many true or false questions would you like to include in your quiz?");
    int l=s.nextInt();
    TrueFalseQuestion[] qu2= new TrueFalseQuestion[l];
    int x;
    for(x=0;x<l;x++){
        System.out.println("Please insert question "+(x+1)+":\n");
        String Q2=s.next();
        System.out.println("Please insert the correct answer");
        boolean A2=s.nextBoolean();
        qu2[x]=new TrueFalseQuestion(Q2,A2);
        System.out.println(qu2[x].GetCorrectAnswer());


}

编辑:这是TrueFalseQuestion代码

public class TrueFalseQuestion extends Question {
   private boolean CorrectB; 

   public TrueFalseQuestion(String qu, boolean b){
         super(qu); 
   } 
   @Override 
   public void GetQuestion() { 
         System.out.println(getMyText()+"\n Is this statement true or false?"); 
   } 
   @Override public String GetAnswer() { 
       System.out.println("Insert Answer: "); 
       boolean MyAnswer=s.nextBoolean(); 
       return Boolean.toString(MyAnswer); 
   }

   @Override public String CheckAnswer() { 
   return Boolean.toString(GetAnswer().equalsIgnoreCase(Boolean.toString(GetCorrectAnswer(‌​))));
    } 
   /** * return the MyAnswer / /* * return the CorrectAnswer / public boolean GetCorrectAnswer() { return CorrectB; } /* * return the MyAnswer */ 

   } 

2 个答案:

答案 0 :(得分:0)

问题是nextInt()在流中并且在next()执行时留下“\ n”     String Q2 = s.next(); 它显示为“\ n”,并没有为您提供输入问题的机会。

试试这个:

System.out.println("How many true or false questions would you like to include in your quiz?");
int l=Integer.parseInt(nextLine());
TrueFalseQuestion[] qu2= new TrueFalseQuestion[l];
int x;
for(x=0;x<l;x++){
    System.out.println("Please insert question "+(x+1)+":\n");
    String Q2=s.nextLine();
    System.out.println("Please insert the correct answer");
    boolean A2=s.nextBoolean();
    qu2[x]=new TrueFalseQuestion(Q2,A2);
    System.out.println(qu2[x].GetCorrectAnswer());
}

答案 1 :(得分:0)

你的问题是你的构造函数:

public TrueFalseQuestion(String qu, boolean b){ 
    super(qu);
}

您没有设置字段CorrectB,因此它默认为默认值,在java中为false

修复

public TrueFalseQuestion(String qu, boolean b){ 
    super(qu);
    CorrectB = b;
}