如何使用while循环

时间:2014-09-24 20:42:56

标签: java

要求用户猜测一个数字,直到猜测等于随机数。按0退出并询问用户是否要再次播放。

我的问题,0退出是,不工作。如何使其与while循环一起使用? 感谢

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


public class Guessing
{
    public static void main(String[]args){
    String playAgain = "y";
    final int MAX =100;
    int randomNumber;
    int numberofGuess = 0;
    int guess  ;
    boolean flag=false;
    Scanner input = new Scanner(System.in);
    Random rand = new Random();

    Scanner inputYes= new Scanner(System.in);

    while(playAgain.equalsIgnoreCase("y"))//do
    { 
        System.out.println("Guess a number between 1 and "+ MAX );
        randomNumber = rand.nextInt(MAX) +1;
        numberofGuess = 0;

        System.out.println( "enter a guess(0 to quit):");
        guess= input.nextInt();
        numberofGuess++;

        if(guess >0)
        if (guess == randomNumber)
        {
            System.out.println("you guessed corect.");
            System.out.println("you guessed " +numberofGuess+ " times");
        }   
        else if(guess < randomNumber)
            System.out.println("you guess is too low.");
        else if(guess > randomNumber)
            System.out.println("you guess is too high.");
        System.out.println("Do you want to play again? (y/n)");
        playAgain = inputYes.nextLine();

    }//while(playAgain.equalsIgnoreCase("y"));

}

}       

1 个答案:

答案 0 :(得分:0)

循环运行直到括号中的表达式为false:

while (true) {
  // this will be executed forever
}

while (false) {
  // this will never be executed
}

a = 0;
while (a == 0) {
  a = 1;
  // this will be executed exactly once, because a is not equal 0 on the second run
}

guess = 1
while (guess != 0) {
  // this will executed until the user enters "0"
  readln(guess);
}

请记住,这是伪代码。它不会编译。