0

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.

1
  • what libgdx has to do with it Commented Sep 6, 2013 at 14:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, simple mistake. I know that :P
1

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.

1 Comment

Yeah I know but for me my form of code is more readable :) and this was the reason for the error :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.