-1

我做了这个猜谜游戏,但我发现了一个错误,我不知道如何修复它。也许你们可以帮忙?

问题是,我只会输入 9 个错误的数字,但它会告诉我我猜了 10 次。我没有。

如果您发现任何其他错误,您能告诉我如何修复这些错误吗?如果你能告诉我下次我可以使用的任何提示/技术,那就太好了。

import java.util.Scanner;

public class main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int number_to_guess = 3;
    int guess;
    //int number_of_guesses = 0;
    Scanner input = new Scanner(System.in);

    System.out.println("Hello, please enter a number between 1 and 10. You only have 10 guesses, so be be smart!!");




    for(int number_of_guesses = 1; number_of_guesses<=10;){
        guess = input.nextInt();
        if (guess >=1 && guess <=10){//is it between 1 and 10

            if(guess == number_to_guess){//is it the right number
                number_of_guesses++;//increase guess number
                System.out.println("Congradulations!!! You guessed the number in " + number_of_guesses + " tries");
                break;//exit the loop
            }

            else{//if its not the right number, then try again
                System.out.println("I'm sorry. Thats not it. Please try again.");
                number_of_guesses++;
                if (number_of_guesses == 10){
                    System.out.println("I'm sorry, but it appears you have guessed 10 times and didn't get the right number. The number was " + number_to_guess);

                    break;
                }
            }
        }

        else{//invalid number entry

            System.out.println("I'm sorry, but your number that you have enter is invalid. Please make sure it is between 1 and 10");
            number_of_guesses--;//the count will go up, even though the guessed an invalid number, so set it back to what it was before
        }
    }



}

}

4

1 回答 1

1

您需要将其移出范围,因为 10 仍然有效

if (number_of_guesses == 10){ System.out.println("对不起,你猜了 10 次,但没有得到正确的数字。数字是 " + number_to_guess); 休息; }

于 2013-03-30T18:47:22.913 回答