終極密碼: 從0~99開始
先亂數產生一個數字
並由使用者自訂義一個數值去做猜測
直到成功為止- package tw.mis.kuas.edu.tw;
- import java.util.Scanner;
- public class Msin {
- public static void main(String[] args) {
- // TODO 自動產生的方法 Stub
- int max =100; //最大
- int min = 0; //最小
- int yournum = 0;
- int count = 0;
- int random_num = (int)(Math.random()*100+1); //亂數產生0~100內的數值
- Scanner scanner = new Scanner(System.in);
-
- while(true)
- {
- count++;
- System.out.print("Please input a number: ");
- yournum = scanner.nextInt();
-
- if(yournum==random_num) //猜中
- {
- System.out.println("You win");
- System.out.println("共猜了"+count+"次");
- }
- else if(yournum<random_num) //太小
- {
- System.out.println("Too Short");
- System.out.println(yournum + "~" + max);
- System.out.println("****************");
- min = yournum; //將最小值設為自己所猜的數值
- }
- else if(yournum>random_num) //太大
- {
- System.out.println("Too Big");
- System.out.println( min + "~" + yournum);
- System.out.println("****************");
- max = yournum; //將最大值設為自己所猜的數值
- }
- }
-
- }
- }
複製代碼 |