数组类的奇怪语法错误

时间:2015-02-22 03:02:17

标签: java arrays

我在我的数组末尾和最后一个结束括号中遇到语法错误。我已经一直在敲我的头了一下。有没有人对如何解决这个问题有任何想法?

public class arrayWords {
    private Words wl;
    private String gamewords[];

    public arrayWords() {
        wl = new Words();
        gamewords = new String[] { "dog", "cat", "coffee", "tag", "godzilla", "gamera", "lightning", "flash",
                "spoon", "steak", "moonshine" };
        setArray();
    }

    public void setArray() {
        for (int i = 0; i < gamewords.length; i++)
            wl.wordList[i].setWord(gamewords[i]);
    }
}

public class Words {
    public Word wordList[];
    public Words() {
        super();
        wordList = new Word[25];
        for (int i = 0; i < 24; i++) {
            wordList[24] = new Word();
        }
    }
}

public class Word {

    String name;
    Words word = new Words();

    public Word() {
        super();
        name = new String("");
    }

    public Word(String w) {
        super();
        name = new String(w);
    }

    public String getWord() {
        return name;
    }

    public void setWord(String s) {
        this.name = new String(s);
    }

}

public class wordTest {
    public static void main(String args[]) {
        Words wl = new Words();
        arrayWords newArray = new arrayWords();

        newArray.setArray();

        for (int i = 0; i < 25; i++)
            System.out.println(wl.wordList[i].getWord());
    }
}

1 个答案:

答案 0 :(得分:4)

问题不在于数组。您正在尝试在类中运行for循环。这应该在方法或主方法中完成。

修改

您可能需要的示例:

public class ArrayWords {
private Words wl;
private String gamewords[];

public ArrayWords() {
    wl = new Words();
    gamewords = new String[] { "dog", "cat", "coffee", "tag", "godzilla", "gamera", "lightning", "flash", "spoon", "steak", "moonshine" };
    setArray();
}

public void setArray() {
    for (int i = 0; i < gamewords.length; i++)
        wl.wordList[i].setWord(gamewords[i]);
}

// getters and setters
}

现在您可以简单地使用main方法创建一个类并将其初始化为

ArrayWords arrayWords = new ArrayWords();
arrayWords...... // what you want to do