字符串数组不会在for循环中添加字符串

时间:2015-12-29 16:01:58

标签: java arrays variables

我正在尝试用Java制作一个刽子手游戏,但我在初始化变量lStorage时遇到了问题。我添加了String[] lStorage,但仍未初始化。

switch(difficulty){
    case 0:
        String[] easywords= new String[]{"integer","project","octopus"};
        int wrong = 12;
        String[] lStorage;
        String easyrnd = (easywords[new Random().nextInt(easywords.length)]);
        System.out.println("The word has " + easyrnd.length() + " Letters");
        while(wrong>=0){
        System.out.println("\n guess a letter");
        String letterguess = consolereader.nextLine();

        if(easyrnd.contains(letterguess)){
            System.out.println("correct " + letterguess + " is the " + "...number" + "Letter"); //need to put in number of letter
            for(int i=12;i>0;i--){
                lStorage[i]=letterguess;
            }

3 个答案:

答案 0 :(得分:3)

数组实际上已经没有初始化。您所做的是宣布它。尝试这样的事情:

//Creating map (Note: Since order is important, use a "Linked" map)
Map<String, String> questionsMap = new LinkedHashMap();

//Storing Q&As:
questionsMap.put("Question 1", "Answer 1");
questionsMap.put("Question 2", "Answer 2");
questionsMap.put("Question 3", "Answer 3");

//Getting individual As from Qs (Qs as Object):
questionsMap.get(questionObject);

//=====This might be as follows in your code specifically:
questionsMap.get(jLabel4.getText());

//Getting individual Qs (from index):
questionsMap.keySet().toArray()[index];

//Getting individual As (from index):
questionsMap.values().toArray()[index];

//Getting individual Key-Value pairs (Q-A pairs):
Entry<String, String> entry = (Entry)questionsMap.entrySet().toArray()[index];
entry.getKey(); //Question
entry.getValue(); //Answer

//Iterating through all Key-Value pairs:
for (Entry<String, String> currentEntry : questionsMap.entrySet()){
  currentEntry.getKey(); //Question
  currentEntry.getValue(); //Answer
}

如果必须动态调整此数组的大小,我建议使用String[] lStorage = new String[size]; 或其他集合类。

答案 1 :(得分:0)

您需要初始化String数组

尝试更改此行

String[] lStorage;

到这个

String[] lStorage = new String[12];

答案 2 :(得分:0)

在Java中,数组是对象(比如C#和许多其他面向对象的语言)。因此,您必须使用new关键字创建/初始化它们。