简体   繁体   中英

Creating Array of Objects from Class I Created

I am working on a Trivia project. I have created a class called Trivia that has all the necessary methods for setting questions and answers etc. In the tester class I need to create an array of 5 Trivia objects that sets the answers, questions, and point values of the 5 questions. I am confused as to how to set the values. I have created the array of Trivia objects and the space for the 5 objects too. Here is my code, thanks!

public class Trivia {
private String question;
private String answer;
private int points;

public Trivia() {
    question = " ";
    answer = " ";
    points = 0;
}

public String getQuestion() {
    return question;
}

public String getAnswer() {
    return answer;
}

public int getPoints() {
    return points;
}

public void setQuestion(String q) {
    question = q;
}

public void setAnswer(String a) {
    answer = a;
}

public void setPoints(int p) {
    points = p;
}

}

(The Tester class)

public class Driver {

public static void main(String[] args) {
    Trivia[] t = new Trivia[5];
    for (int i = 0; i <= 5; i++) {
        t[i] = new Trivia();
    }

}

}

This line creates a new Trivia and stores it in an array:

for (int i = 0; i <= 5; i++) {
    t[i] = new Trivia();
}

You can use this to assign a question. However all questions will then be the same...

for (int i = 0; i <= 5; i++) {
    t[i] = new Trivia();
    t[i].setQuestion("bla");
}

You can might want to create individual questions after the loop:

for (int i = 0; i <= 5; i++) {
    t[i] = new Trivia();
}
t[0].setQuestion("question1");

Proceeding to develop your application you will have to think about a convinient way of storing the question. Hardcoding them into the java code is good for the start but you will have to recompile, everytime a question changes.

Maybe using a .property file with all the question texts could be an option.

You can do somenthng like this:

    Trivia[] t = new Trivia[5];
    for (int i = 0; i < 5; i++) {
        Trivia tx = new Trivia();
        tx.setQuestion("xxxx");
        tx.setAnswer("xxxx");
        tx.setPoints(0);
        t[i] = tx;
    }

Set the values using the setter methods you have declared in your class.

Example:

t[i].setAnswer("answer");

Maybe something like this:

    Trivia[] t = new Trivia[5];
    for (int i = 0; i <= 5; i++) {
        t[i] = new Trivia();
        t[i].setQuestion("What is "+i+"+"+i+"?");
        t[i].setAnswer(""+(2*i));
     }

This sets the questions and answers using you setter-Methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM