【问题标题】:Method for checking for letter in word (Hangman code)Word中的字母检查方法(Hangman代码)
【发布时间】:2017-12-11 06:22:38
【问题描述】:

作业是为 Evil Hangman 代码组合的几种方法。这个具体的方法赋值是:

遍历单词并返回一个数组,该数组包含单词中字母位置的字符代码,否则为0。

参数:

theWord - 程序选择的单词

letter - 用户输入的字母

guess - 目前猜到的字母

返回: 一个整数数组,如果用户正确猜到了 Word 中的一个字母,则将字符代码插入该位置。

public static int[] checkLetterInWord(java.lang.String theWord, char letter, int[] guess) {
    int [] position = new int [guess.length];
    int correctGuesses=0;
    int incorrectGuesses=0;
    for (int i=0; i<position.length; i++) {
        for (int j=0; j<theWord.length(); j++) {
        if (theWord.charAt(j)==letter) {
            position[i]=j;
            correctGuesses++;
        }
        else if(theWord.charAt(j)!=letter) {
            position[i]=0;
            incorrectGuesses++;
        }

我不确定我所采用的方法是否有效,因为在完成整个课程之前我无法检查。如果有人能告诉我它是否有任何问题,我将不胜感激!

【问题讨论】:

    标签: java


    【解决方案1】:

    使用列表

    public static java.util.List<Integer> checkLetterInWord(final java.lang.String theWord, final char letter) {
        final java.util.List<Integer> returned = new java.util.ArrayList<Integer>();
        if (theWord != null) {
            for (int i = 0; i < theWord.length(); i++) {
                if (theWord.charAt(i) == letter) {
                    returned.add(Integer.valueOf(i));
                }
            }
        }
        return returned;
    }
    

    使用数组

    public static int[] checkLetterInWord(final java.lang.String theWord, final char letter) {
        if (theWord != null) {
            final int returned[] = new int[theWord.length()];
            for (int i = 0; i < theWord.length(); i++) {
                if (theWord.charAt(i) == letter) {
                    returned[i] = i;
                } else {
                    returned[i] = -1;
                }
            }
            return returned;
        }
        return new int[0];
    }
    

    【讨论】:

    • 不知道有没有其他方法可以做到?我们还没有在我的 CS 课上学过列表,所以我认为我不会使用它们。
    • 好的。请参阅编辑后的答案。不要使用零,使用-1。因为零是一个有效的索引
    猜你喜欢
    • 1970-01-01
    • 2011-06-20
    • 2018-04-02
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多