Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从数组返回单个字符串_Java - Fatal编程技术网

Java 从数组返回单个字符串

Java 从数组返回单个字符串,java,Java,我正试图用libGDX编写一个简单的游戏,但这个问题阻止了创建这个游戏的整个过程。 这里有两节课 public class Question { private static float getFontX() { return Assets.font.getBounds(Database.getText()).width / 2; } private static float getFontY() { return Assets.font.getBounds(Database

我正试图用libGDX编写一个简单的游戏,但这个问题阻止了创建这个游戏的整个过程。 这里有两节课

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;

}
第二类是数据库,它包含问题

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];
}
}
这里面有个问题

return questions[0]
因为如果我在那里写的话

return "This will work";

一切正常。

您需要将初始化块更改为静态初始化块

static {
    questions[0] = "Some question1";
    questions[1] = "Some question2";
}
如果不创建数据库类的新实例,如:

Database db = new Database();

不会调用动态初始化块。这就是您需要使用随类调用的静态初始化块的原因。

您可以将
数据库中的数组声明为:

public class Database {

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


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

}

然后返回所需的
字符串。

libgdx与itThanks的关系,简单的错误。我知道:是的,我知道,但对我来说,我的代码形式更具可读性:),这就是产生错误的原因:S