试图找到一种不同的方式来编写这段代码

时间:2014-12-11 00:59:06

标签: java if-statement

我已经编写了这段代码,现在我正在练习,并且我正在尝试以不同或更有效的方式编写代码。基本上这个代码要求用户输入一个单词,第二个玩家用6次尝试猜测单词的字母,最后有一个最后一次猜测整个单词的机会。关于如何以简单的方式编写此代码的任何建议?

static int NUM_OF_TRIES = 6;

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Player 1 please enter the word");
    String word = keyboard.next();

    for (int i = 0; i < NUM_OF_TRIES; i++) {
        System.out.println("Enter your guess please");
        String guess = keyboard.next();
        boolean a = true;
        for (int j = 0; j < word.length(); j++) {
            if (guess.charAt(0) == word.charAt(j)) {
                System.out.println(" at position " + (j + 1));
                a = false;
                break;
            }

        }
        if (a) {
            System.out.println("Sorry not letter " + guess.charAt(0));
            continue;
        }
    }

    System.out.println("Enter your last guess: ");
    String wordComp;
    wordComp = keyboard.next();

    if (wordComp.equals(word)) {
        System.out.println("You got it!");
    } else {
        System.out.println("Sorry you lost!");
    }

}

}

2 个答案:

答案 0 :(得分:0)

---首先,你必须确保

word.length <=guess.length

或者你会遇到异常.---编辑:这是不正确的

我现在无法在我的手机上进行测试,但就我所知,如果要猜多少的字有多次相同的字母,你就会遇到问题,因为找到相同的第一个字母后,你就会突然离开。

如评论中所述,可以通过类似

的方法进行比较
private static List<Integer> getLetterIndices(String word, char letter);

然后你不需要你的布尔值来表示正确的猜测,但找到了一个索引列表

当然你可以做一个面向对象的方法而不是静态主方法(不是它实现得更快或性能更好,只是为了练习),也许就是这样:

public class WordToGuess{
    private Map<Character,List<Integer>> letter2indices;//...
    public WordToGuess(String word){
        parseIndices(word);
    }
    //parse indices of each letter to the map
    private void parseIndices(String word); 

    public List<Integer> getLetterIndices(char letter);
}

答案 1 :(得分:0)

嗯,这是一个较短的版本:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Player 1 please enter the word");
    String word = keyboard.next();

    for (int i = 0; i < NUM_OF_TRIES; i++) {
        System.out.println("Enter your guess please");
        String guess = keyboard.next();
        int index = word.indexOf(guess.charAt(0));

        if (index == -1)
            System.out.println("Sorry not letter " + guess.charAt(0));
        else
            System.out.println(" at position " + (index + 1));
    }

    System.out.println("Enter your last guess: ");
    String wordComp = keyboard.next();

    if (wordComp.equals(word))
        System.out.println("You got it!");
    else
        System.out.println("Sorry you lost!");
}