数字猜测回合

时间:2017-11-10 13:02:46

标签: java numbers

我想猜数字游戏。一轮我的程序工作,我猜一个数字。我希望用户可以输入他想玩的东西(1-20),但是我的问题是这不符合想法。我尝试使用布尔值,但在我猜到1轮数后,它不会开始下一轮。 In函数类似于scanner,但我有一个java类,因此我使用它。

public class GuessNumber {

public static void main(String[] args) {

    System.out.println("round 1-20");
    int roundTyped = In.readInt();

    int rndN = (int) (Math.random()*100)+1;
    int typedN = 0;
    int trys = 0;
    boolean active = true;
    int round = 0;

    while (active) {
        while (typedN != rndN) {
            trys++;
            System.out.println(trys + ". Versuch:");
            typedN = In.readInt();

            if(typedN < 1 || typedN > 100) {
                System.out.println("ungueltig");
            }else if(typedN < rndN) {
                System.out.println("groesser");
            }else if(typedN > rndN) {
                System.out.println("kleiner");
            }else if(typedN == rndN) {
                System.out.println("korrrekt");
            }
        }
        round++;
        if (round == roundTyped) {
            active = false;
        }

    }

}

2 个答案:

答案 0 :(得分:0)

您可以在程序开头只设置一次猜测的数字。因此,在用户猜出一次正确的数字之后,剩余的轮数将立即完成(内部的条件将始终为真)。 我建议你使用调试器来查找这些问题。当您单步执行程序时,会立即发现正在发生的事情。

答案 1 :(得分:0)

不需要两个while循环,您可以为while添加几个条件,并使用两个相同的roundtrys变量。

但您最大的问题是,在检查false是否为true之前,您实际上已将其设置为 System.out.println("round 1-20"); int roundTyped = In.readInt(); int rndN = (int) (Math.random()*100)+1; int typedN = 0; int nTrysAllowed = 10; // The max number of tries int trys = 0; int round = 0; while (round < roundTyped) { while (typedN != rndN && trys < nTrysAllowed) { trys++; System.out.println(trys + ". Versuch:"); typedN = In.readInt(); if(typedN<1 || typedN >100) { System.out.println("ungueltig"); } else if(typedN < rndN) { System.out.println("groesser"); } else if(typedN > rndN) { System.out.println("kleiner"); } else { System.out.println("korrrekt"); } } // Here you can reduce the max number of tries for example or do whatever you want. For example: round++; if (typedN == rndN) { // New number to guess rndN = (int) (Math.random()*100)+1; // Difficulty nTrysAllowed--; trys = 0; } else { System.out.println("Game done you can't go to next round, you lose this one."); round = roundTyped; } }

尝试类似的东西:)

{{1}}
相关问题