2014-09-24 191 views
-4

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

我的问题,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")); 

} 

}  
+0

你在第一个if和break语句周围缺少大括号来结束循环。 – Brian 2014-09-24 20:46:00

+0

请提出问题时请格式化您的代码 – nem035 2014-09-24 20:56:39

回答

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

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

+0

输入0时仍然无效 – JayLo 2014-09-24 22:05:42