简单的Java猜测程序。继续

时间:2015-11-23 08:45:24

标签: java eclipse if-statement boolean

我只是在玩java并想在用户做一个简单的程序;我必须猜测/输入正确的数字,直到它正确为止。我能做什么,程序可以继续运行,打印出“再猜一猜”,直到用户/我输入正确的数字。也许布尔值?我不确定。这就是我到目前为止所拥有的。

import java.util.Scanner;

public class iftothemax {
    public static void main(String[] args) {

    int myInt = 2;

    // Create Scanner object
    Scanner input = new Scanner(System.in);

    //Output the prompt
    System.out.println("Enter a number:");

    //Wait for the user to enter a number
    int value = input.nextInt();

    if(value == myInt) {
        System.out.println("You discover me!");
    }
    else {
        //Tell them to keep guessing
        System.out.println("Not yet! You entered:" + value + " Make another guess");
        input.nextInt();

    }
}

3 个答案:

答案 0 :(得分:6)

您可能希望使用while循环重复某些代码:

pygame.quit()

答案 1 :(得分:1)

这个程序可以解决问题:

public static void main(String [] args){
    int myInt = 2;
    int value = 0;
    Scanner input = new Scanner(System.in);
    boolean guessCorrect = false;
    while(!guessCorrect){
        System.out.println("Not yet! You entered:" + value + " Make another guess");
        value = input.nextInt();
        if(value == myInt){
            guessCorrect = true
        }
    }
    System.out.println("You discover me!");
}

答案 2 :(得分:0)

简单介绍一个循环。

import java.util.Scanner;

public class iftothemax {
    public static void main(String[] args) {

        int myInt = 2;

        // Create Scanner object
        Scanner input = new Scanner(System.in);

        for(;;) {
            //Output the prompt
            System.out.println("Enter a number:");

            //Wait for the user to enter a number
            int value = input.nextInt();


            if(value == myInt) {

                System.out.println("You discover me!");
                break;
            }
            else {
                //Tell them to keep guessing
                System.out.println("Not yet! You entered:" + value + " Make another guess");

            }
        }

    }
}