本文實例講述了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("你 主站蜘蛛池模板: 新巴尔虎左旗| 桑植县| 滦平县| 麻城市| 中山市| 洛川县| 麦盖提县| 崇州市| 伊金霍洛旗| 宜城市| 嘉黎县| 和林格尔县| 镇平县| 新乡市| 齐河县| 赤城县| 河北省| 宝兴县| 天镇县| 常宁市| 修水县| 淳化县| 吉林省| 鲁山县| 全州县| 米泉市| 灯塔市| 思茅市| 九龙县| 黎川县| 岚皋县| 茂名市| 星座| 武定县| 万州区| 宿松县| 博爱县| 云南省| 长兴县| 定西市| 霍邱县|