如何在Java中创建条件循环

时间:2015-01-04 16:22:45

标签: java

我正试图在java中制作一个简单的猜数游戏。该程序应该生成0到10之间的随机数,我希望用户猜测它。如果猜测的数字较低,则程序显示一条消息,表明猜测的数字较低,并希望用户猜测它直到正确的数字。我做了这个程序如下。但是,它立即完成。我怎么能修改我的代码让用户猜到它,直到正确的数字猜到?我认为这是有条件的循环,但我无法弄明白。

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Random rnd = new Random();
        int realNumber = rnd.nextInt(11);

        System.out.println("generated number is "+ realNumber + " (for test purposes)"); //Displaying generated number for test purposes

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your guess number between 0 and 10 ====>");
        int guessedNumber = input.nextInt();

        if(guessedNumber > realNumber){
            System.out.println("My number is lower than " + guessedNumber + " guess lower!");
        }else if(guessedNumber < realNumber){
            System.out.println("My number is higher than " + guessedNumber + " guess higher!");
        }else{
            System.out.println("Yes! That's my number!");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

一个例子:

boolean wrongAnswer = true;
while(wrongAnswer){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your guess number between 0 and 10 ====>");
    int guessedNumber = input.nextInt();

    if(guessedNumber > realNumber){
        System.out.println("My number is lower than " + guessedNumber + " guess lower!");

    }else if(guessedNumber < realNumber){
        System.out.println("My number is higher than " + guessedNumber + " guess higher!");
    }else{
        wrongAnswer = false;
        System.out.println("Yes! That's my number!");
    }
}

答案 1 :(得分:1)

boolean flag = true;   // initialize flag with true value;

do{   
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your guess number between 0 and 10 ====>");
    int guessedNumber = input.nextInt();

    if(guessedNumber > realNumber){
        System.out.println("My number is lower than " + guessedNumber + " guess lower!");

    }else if(guessedNumber < realNumber){
        System.out.println("My number is higher than " + guessedNumber + " guess higher!");
    }else{
        System.out.println("Yes! That's my number!");
        flag = false;   // when condition satisfies change the flag to false to break the loop.
    }
}while(flag) 

你必须使用循环,首先用true初始化你的标志,然后当你的条件满足时将它设为false以打破你的循环;