由計算機產生0-9之間的隨機整數,用戶輸入猜想的數據,統計用戶猜想的次數。產生隨機數可使用Math.rangom()靜態方法,該方法返回正的double類型浮點數位於(0.0 1.0】間。

 package testrandom;java

import java.util.Random;dom

import java.util.Scanner;spa


public class Main {class

    public static void main(String[] args) {
           Random ra = new Random();
        Scanner sc = new Scanner(System.in);
        int temp = ra.nextInt(10);
        System.out.println(temp);
        String s = "";
        int count = 0;
        while(true){
               System.out.println("請經過鍵盤輸入您猜的數字:");
               s = sc.next();
               if(s.matches("
//d*"))
               {
                      int in = Integer.parseInt(s);
                      if(in == temp)
                        {
                          System.out.println("您猜對了!");
                          count +=1;
                          break;
                        }
                       else
                        {
                          System.out.println("啊呀呀,仍是不對,再來一次?!");
                          count++;
                         }
                }
                   else
                    {
                     System.out.println("請輸入數字格式!");
                     count++;
                     continue;
                    }
  }
        if(count<=3)
        {
          System.out.println("您只猜了 " + count + " 次");
         }
        else{
               System.out.println("多多努力,您總計猜了 " + count + " 次");
             }
}
}
test