【问题标题】:Simple Java Guessing program. Continuing简单的 Java 猜测程序。继续
【发布时间】:2015-11-23 08:45:24
【问题描述】:

我只是在玩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();

    }
}

【问题讨论】:

  • 使用while循环,循环直到值正确

标签: java eclipse if-statement boolean


【解决方案1】:

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

while (value != myInt) {
    System.out.println("Not yet! You entered: " + value + ". Make another guess");
    value = input.nextInt();
}
System.out.println("You discovered me!");

【讨论】:

    【解决方案2】:

    这个程序可以解决问题:

    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!");
    }
    

    【讨论】:

    • @ParkerHalo,谢谢没有注意到。
    【解决方案3】:

    只需引入一个循环。

    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");
    
                }
            }
    
        }
    }
    

    【讨论】:

    • @ParkerHalo 为什么你认为循环开始得太早了?我不知道规格。
    • 你相应地编辑了帖子,所以现在循环不会太早开始......我仍然认为在他们知道之前教 java-newlings 东西作为 for(;;)break 并不好一个循环是!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多