读取用户输入,直到匹配给定的数字

时间:2016-11-17 19:24:46

标签: java

这是我的代码

public class JavaAsig8 {

  public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    int number;

    System.out.print("Enter a whole number: ");
    number = stdIn.nextInt();
    Random r = new Random();
    for (int i = 0; i < number; i++) {
        Random rn = new Random();
        int answer = rn.nextInt(10) + 1;
        System.out.println(answer);
    }
  }
} 

我需要能够要求用户猜测该数字,直到它等于随机数。

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public class Main
{
    public static void main(String args[]) 
    {
        Random r = new Random();
        int givenNumber = r.nextInt(10) + 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a whole number: ");
         while(true)
         {
             if(s.nextInt() == givenNumber)
             {
                 System.out.println("You guessed it right! Answer is: " + givenNumber);
                 break;
             }
         }
     }
 }