返回列表 發帖
本帖最後由 晏有聰 於 2012-10-9 09:36 編輯
  1. /* 猜數字遊戲1-100,會計算猜幾次 */
  2. import java.io.Console;
  3. public class ch26_2
  4. {
  5.    public static void main (String showdemo[])
  6.    {
  7.       Console console=System.console();
  8.    
  9.       int random_value,input1,count=1;
  10.       int range1=1,range2=100;      
  11.       random_value=(int)((Math.random())*100+1);
  12.       
  13.       System.out.print("請猜測一個數字介於1-100的整數=");  
  14.       input1=Integer.parseInt(console.readLine());
  15.       
  16.       while (true)
  17.       {
  18.          if(input1>0 && input1<=100)
  19.          {            
  20.                if(input1==random_value)
  21.                {
  22.                   System.out.print("Bingo,您猜對了  ");
  23.                   System.out.println("您猜了"+count+"次");
  24.                   break;                 
  25.                }         
  26.                else
  27.                {
  28.                    range2=((input1>random_value)&&(input1<range2))?input1:range2;                                
  29.                              
  30.                    range1=((input1<random_value)&&(input1>range1))?input1:range1;                  
  31.                  
  32.                    System.out.print("請再猜一次,範圍介於 "+range1+"~"+range2+"=");

  33.                    input1=Integer.parseInt(console.readLine());

  34.                    count=count+1;

  35.                    continue;  
  36.                }                              
  37.          }
  38.          else
  39.          {
  40.              System.out.print("來亂的嗎 ? 請猜1-100之間的整數=");
  41.              count=count+1;
  42.          }
  43.          input1=Integer.parseInt(console.readLine());     
  44.       }

  45.    }
  46. }
複製代碼

TOP

返回列表