getter和setter的数组没有得到结果

时间:2017-12-11 13:00:04

标签: java setter getter

我正在尝试使用数组工作getter和setter,我创建了2个对象问题和答案与他们的get和setter。我还创建了两个名为Question的数组,一个名为Answer的数组。

 class Question {
    private String[] questions;

    public void setQuestion(String questions[]) {
        this.questions = questions;
    }

    public String[] getQuestion() {
        return questions;
    }
}

class Answer {
    private String[] answers;

    public void setAnswer(String answers[]) {
        this.answers = answers;
    }   

    public String[] getAnswer() {
        return answers;
    }
}

但是在尝试打印问题时,它无法识别`getQuestion'

for (int n = 0; n<getQuestion.length; n++) {
    System.out.println("Question" + (n+1));
    System.out.println(getQuestion(Question[n]);
}

2 个答案:

答案 0 :(得分:1)

getQuestion是您的问题类的一种方法,应该像questions.getQuestion()一样调用。也许你想为getQuestion返回一个问题吗?

答案 1 :(得分:1)

您需要创建Question类的实例,然后调用getQuestion()方法。

根据您的目的,您可能还需要使用Question修饰符公开public课程

注意 您也可以像Pavneet_Singh指出的那样制作getQuestion()方法static,从而无需创建Question类的新实例。

更新了代码

Question question = new Question();

for (int n = 0; n<question.getQuestion().length; n++) {
    System.out.println("Question" + (n+1));
    //note that this wont work, you dont pass any parameters to the getQuestion() method
    System.out.println(getQuestion(Question[n]);
}

对您的代码进行了一些改进;

public class Question {

   private String question;

   //Use Question constructor to populate the question string
   public Question( String question ){
      this.question = question;
   }

   //get the question
   public String getQuestion(){
     return question;
   }
}

//follow same pattern here
public class Answer {

   private String answer;

   public Answer( String answer ){
      this.answer = answer;
   }

   public String getAnswer(){
     return answer;
   }
}

主要方法

//Create array of type Question
Question[] questions = new Question[3];

//create new questions and use constructor to set string question
Question question1 = new Question('What is your name?');
Question question2 = new Question('What is your age?');
Question question3 = new Question('What is your favourite color?');

//add questions to array
questions.add(question1);
questions.add(question2);
questions.add(question3);
int counter = 0;

//loop through the array
for (Question question : questions) {
   System.out.println("Question " + (counter+1));
   System.out.println(question.getQuestion();
   counter++;
}

我会让你弄清楚如何将问题映射到答案