本帖最後由 晏有聰 於 2012-10-9 09:36 編輯
- /* 猜數字遊戲1-100,會計算猜幾次 */
- import java.io.Console;
- public class ch26_2
- {
- public static void main (String showdemo[])
- {
- Console console=System.console();
-
- int random_value,input1,count=1;
- int range1=1,range2=100;
- random_value=(int)((Math.random())*100+1);
-
- System.out.print("請猜測一個數字介於1-100的整數=");
- input1=Integer.parseInt(console.readLine());
-
- while (true)
- {
- if(input1>0 && input1<=100)
- {
- if(input1==random_value)
- {
- System.out.print("Bingo,您猜對了 ");
- System.out.println("您猜了"+count+"次");
- break;
- }
- else
- {
- range2=((input1>random_value)&&(input1<range2))?input1:range2;
-
- range1=((input1<random_value)&&(input1>range1))?input1:range1;
-
- System.out.print("請再猜一次,範圍介於 "+range1+"~"+range2+"=");
- input1=Integer.parseInt(console.readLine());
- count=count+1;
- continue;
- }
- }
- else
- {
- System.out.print("來亂的嗎 ? 請猜1-100之間的整數=");
- count=count+1;
- }
- input1=Integer.parseInt(console.readLine());
- }
- }
- }
複製代碼 |