Jakub
Jakub

Reputation: 2141

Returning single String from array

Im trying to write simple game in libGDX, but this problem stops whole process of creating that game. Here is two classes.

public class Question {

private static float getFontX() {
    return Assets.font.getBounds(Database.getText()).width / 2;
}

private static float getFontY() {
    return Assets.font.getBounds(Database.getText()).height / 2;
}

public static void draw(SpriteBatch batch) {

    Assets.font.draw(batch, Database.getText(),
                             TOFMain.SCREEN_WIDTH / 2 - getFontX(),
                             getFontY() + 250 + TOFMain.SCREEN_HEIGHT / 2);
           //drawing some text from database on screen in the middle of screen;

}

and the second class is Database it contains questions

public class Database {

private static String questions[] = new String[2];
{
    questions[0] = "Some question1";
    questions[1] = "Some question2";
}

static public String getText() {
    return questions[0];
}
}

There is a problem in

return questions[0]

because if I write there for example

return "This will work";

everything is ok.

Upvotes: 0

Views: 58

Answers (2)

arjacsoh
arjacsoh

Reputation: 9232

You can declare the array in Database class as:

public class Database {

private static String questions[] = new String[]{
    "Some question1", "Some question2"
};


static public String getText() {
    return questions[0];
}

}

Then it returns the String you want.

Upvotes: 1

Simon Dorociak
Simon Dorociak

Reputation: 33495

You need to change your initialisation block to static initialisation block.

static {
    questions[0] = "Some question1";
    questions[1] = "Some question2";
}

If you won't create new instance of Database class like:

Database db = new Database();

dynamic initialisation block won't be called. This is reason why you need to use static initialisation block that is called with class.

Upvotes: 1

Related Questions