【问题标题】:Changing the value inside an Array List?更改数组列表中的值?
【发布时间】:2016-05-16 01:44:49
【问题描述】:
for(int i = 0; i <= gameWord.length()-1; i++)
    {
        if(guessLetter.charAt(0) == (gameWord.charAt(i)))
        {
            hideword[i] = guessLetter.charAt(0);
        }
        else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
        {
            System.out.print("_" + " ");
        }
    }

我正在制作一个刽子手游戏,我创建了一个名为 hideword 的数组列表。 Hideword 为用于游戏的单词中的每个字母打印一个下划线。我正在尝试纠正一种将下划线与用户猜测的字母交换的方法。但是这段代码

hideword[i] = guessLetter.charAt(0);

不起作用。它给了我“需要数组,但找到了 java.util.ArrayList

有人帮忙吗?

【问题讨论】:

标签: java arrays string arraylist


【解决方案1】:

那么,hideword 必须是一个数组列表。使用hideword.set(index, character) 进行赋值,而不是像访问数组一样访问它。

【讨论】:

    【解决方案2】:

    ArrayList 不是一个数组,它是一个 List 实现(但是,它的实现支持一个数组 - 因此得名)。

    hideword 声明为char 的数组:

    private char[] hideword;
    

    并在使用前对其进行初始化:

    hideword = new char[gameword.length];
    

    你的代码,在不改变其基本意图的情况下,可以大大简化:

    • 长度不需要减去1,只需更改比较运算符
    • 没有必要在 else 中包含您的 if - 我们已经知道它不相等,因为我们在 else 块中
    • 与其做无用的打印,不如给数组槽分配下划线
    • 最后打印一张

    像这样:

    for (int i = 0; i < gameWord.length(); i++) {
        if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
            hideword[i] = guessLetter.charAt(0);
        } else {
            hideword[i] = '_';
        }
    }
    // print hideword
    

    如果 hideword 不存在,而您只需 System.out.print() 测试每个字符,您的代码会更简单。

    【讨论】:

    • 你确定我可以使用 char 作为数组列表吗?如果我正在使用它,我无法打印任何东西
    • @ian 这不是一个数组列表!!!这是一个数组。一种打印方式:System.out.println(Arrays.toString(array).replaceAll("\\W", ""));
    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多