1 import java.text.SimpleDateFormat; 2 import java.util.Date; 3 import java.util.Scanner; 4 5 //主函數 6 public class calssOne { 7 8 public static void main(String[] args) { 9 10 //shit+Ctrl+o11 int result;12 //隨機產生一個在100以內的數字13 int number = (int)(Math.random()*100);14 System.out.println("\n***********猜數位小遊戲,你hold得住嗎?*********");15 System.out.println("\n ********隨機數字產生:不告訴你!*********\n");16 System.out.println("\n ***********答案:"+number+"***************\n");17 System.out.println("讓我們動動腦筋來猜一猜吧,小提示:他是一個從1到100的整數");18 long sTartTime=System.currentTimeMillis();//定義一個時間變數19 for(int i=1;i<100;i++){20 System.out.println("請輸入你第"+i+"次的猜測");21 result=calssOne.guess(i);//通過調用輸入函數得到輸入結果22 //通過比較輸出控制台23 if(result>number)24 System.out.println("不好意思,您所猜的數字大於謎底數字!");25 else if(result < number)26 System.out.println("不好意思,您所猜的數字小於謎底數字!");27 else {28 SimpleDateFormat sNowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");29 long sEndTime=System.currentTimeMillis();30 System.out.println("\n ***********正確答案:"+number+"***************\n");31 if(i==1){32 System.out.println("perfect!!恭喜您!一次就中!!");33 }34 else if(i<10){35 System.out.println("good job! 您總共猜了"+i+"次, 還要繼續加油!!");36 }37 else{38 System.out.println("not bad! 您總共猜了"+i+"次, 任重而道遠啊!");39 }40 System.out.println("目前時間 :" +sNowDate.format(new Date()));// new Date()為擷取當前系統時間41 //System.out.println("目前時間 :" +sNowDate);42 System.out.println("所用時間 :" +(sEndTime-sTartTime)/1000+"秒");43 return;44 }45 }46 }47 //輸入函數48 public static int guess(int i){49 //通過引入import java.util.Scanner類包50 Scanner sc=new Scanner(System.in);51 int result;52 try{53 //使在控制台輸入的內容必須為數字54 result=sc.nextInt();55 return result;56 }57 catch (Exception e) {58 // TODO: handle exception 59 System.out.println("你輸入的不是數字,請重新輸入第"+i+"個數字");60 //調用本函數重新輸入61 guess(i);62 }63 return 0;64 }65 }