简单的猜谜游戏。 “你的第一个猜测是......”

时间:2016-01-21 06:34:43

标签: java if-statement java.util.scanner

我正在用三次尝试创建这个简单的猜谜游戏,但我需要帮助添加代码,以便它可以显示“第一次猜测”,然后是用户输入的整数,“第二次猜测”等...我目前只有“输入你的猜测”这是第一次尝试。我需要做什么?我很困惑如何去做这件事。对不起,如果问题很混乱。

import java.util.Scanner;

public class guess {

public static void main(String[] args) {

    int randomN = (int) (Math.random() * 10) + 1;

    Scanner input = new Scanner(System.in);
    int guess;
    System.out.println("Enter a number between 1 and 10.");
    System.out.println();
    int attempts = 0;

    do {
        attempts++;

        System.out.print("Enter your guess: ");
        guess = input.nextInt();

        if (guess == randomN) {
            System.out.println("You won!");
        } else if (guess < 1 || guess > 10) {
            System.out.println("out of range");
            attempts = +1;
        } else if (guess > randomN) {
            System.out.println("Too high");
        } else if (guess < randomN) {
            System.out.println("Too low");
        }

    } while (guess != randomN && attempts < 3);

    if (guess != randomN && attempts == 3) {
        System.out.println("Number is " + randomN);
    }


    }

}

1 个答案:

答案 0 :(得分:0)

您可以在main之外创建另一个静态方法,您可以根据attempts输出自定义消息。

public static String describe(int attempts) {
    switch(attempts) {
        case 1: return "First guess: ";
        case 2: return "Second guess: ";
        case 3: return "Third guess: ";
        default: return "Enter your guess: "; //should not happen
    }
}

然后在main中使用它:

...
do {
    attempts++;

    System.out.print(describe(attempts));
...
}