Java編寫猜數字小遊戲_java

來源:互聯網
上載者:User

本文執行個體講述了java實現的簡單猜數字遊戲代碼。分享給大家供大家參考。

以下是Java語言寫的一個猜數字小遊戲引用片段:

 import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner;  //主函數 public class calssOne {      public static void main(String[] args) {        //shit+Ctrl+o    int result;    //隨機產生一個在100以內的數字    int number = (int)(Math.random()*100);    System.out.println("\n***********猜數位小遊戲,你hold得住嗎?*********");    System.out.println("\n  ********隨機數字產生:不告訴你!*********\n");    System.out.println("\n  ***********答案:"+number+"***************\n");    System.out.println("讓我們動動腦筋來猜一猜吧,小提示:他是一個從1到100的整數");    long sTartTime=System.currentTimeMillis();//定義一個時間變數    for(int i=1;i<100;i++){     System.out.println("請輸入你第"+i+"次的猜測");     result=calssOne.guess(i);//通過調用輸入函數得到輸入結果     //通過比較輸出控制台     if(result>number)       System.out.println("不好意思,您所猜的數字大於謎底數字!");     else if(result < number)       System.out.println("不好意思,您所猜的數字小於謎底數字!");     else {       SimpleDateFormat sNowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");       long sEndTime=System.currentTimeMillis();       System.out.println("\n  ***********正確答案:"+number+"***************\n");       if(i==1){         System.out.println("perfect!!恭喜您!一次就中!!");       }       else if(i<10){         System.out.println("good job! 您總共猜了"+i+"次, 還要繼續加油!!");       }       else{         System.out.println("not bad! 您總共猜了"+i+"次, 任重而道遠啊!");       }       System.out.println("目前時間 :" +sNowDate.format(new Date()));// new Date()為擷取當前系統時間       //System.out.println("目前時間 :" +sNowDate);       System.out.println("所用時間 :" +(sEndTime-sTartTime)/1000+"秒");     return;     }    }   }   //輸入函數   public static int guess(int i){     //通過引入import java.util.Scanner類包    Scanner sc=new Scanner(System.in);    int result;    try{      //使在控制台輸入的內容必須為數字      result=sc.nextInt();      return result;    }    catch (Exception e) {      // TODO: handle exception     System.out.println("你輸入的不是數字,請重新輸入第"+i+"個數字");    //調用本函數重新輸入    guess(i);    }    return 0;   } }

Java語言寫的一個猜數字小遊戲功能,分享給大家!對於剛剛學習編程的同學可以看看,希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.