Java循环使用相同的方法,但是使用不同的system.out

时间:2019-02-23 15:00:18

标签: java

我正在上Java入门课程,我们有一个处理hang子手游戏的项目。我已经完成了大部分代码,但是有一种方法可以简化代码。

在下面的代码中,该程序将在每轮(最多3轮)中输出一条消息,然后使用game.nextRound()将其设置为一个使用变量word1word2,{ {1}}。该变量将按降序顺序调用。

word3

Hangman.java

import java.util.Scanner;

public class Game {

    public static void main(String[] args) {

        String word1 = "ruby";
        String word2 = "python";
        String word3 = "swift";

        Scanner kb = new Scanner(System.in);

        Hangman game = new Hangman();

        System.out.println("Let's play a round of hangman.");
        System.out.println("We are playing hangman");

        game.nextRound(word1);

        while (true) {
            System.out.println("");
            System.out.println("The disguised word is " + game.disguised());
            System.out.println("Guess a letter:");
            char guess = kb.next().charAt(0);
            boolean isFound = game.guessLetter(guess);
            if (isFound) {
                game.result();
                if (game.disguised().equals(game.secret())) {
                    game.found();
                    break;
                }
            } else {
                game.result();
            }
        }

        System.out.println("");
        System.out.println("Let's play a second round of hangman.");
        System.out.println("We are playing hangman");

        game.nextRound(word2);

        ....
        ....
        ....

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

-将字符串word1word2word3放入类型为String的数组中。    假设

String[] words = {"ruby", "python", "swift"};

-将int计数器初始化为0。

int c = 0;

-在while循环的if和else语句中添加game.nextRound(words[c++]);

答案 1 :(得分:0)

您可以使用ArrayList,也可以使用counter来表示游戏编号。

public class Game {

    public static void main(String[] args) {

        int count = 1;

        List<String> words = new ArrayList<>();
        words.add("ruby");
        words.add("python");
        words.add("swift");

        for (String word : words) {

            System.out.println("Let's play a round of " + count + "hangman.");
            System.out.println("We are playing hangman");

            Hangman game = new Hangman();

            game.nextRound(word);

            while (true) {
                System.out.println("");
                System.out.println("The disguised word is " + game.disguised());
                System.out.println("Guess a letter:");
                char guess = kb.next().charAt(0);
                boolean isFound = game.guessLetter(guess);
                if (isFound) {
                    game.result();
                    if (game.disguised().equals(game.secret())) {
                        game.found();
                        break;
                    }
                } else {
                    game.result();
                }
            }
            count++;
        }
    }
}