1. 程式人生 > >猜數遊戲

猜數遊戲

問題 是否 match out else return 退出 input main

使用Java編寫完成常見算法的程序,達到熟悉並運用java語言解決基本問題的目的。具體的題目可能在行課過程中會有調整,常見的參考的題目如下。

猜數遊戲,要求:

(1)編寫一個方法用於產生1-1000之間的隨機數;

(2)編寫一個方法用於完成兩個數的比較,參數(隨機數,用戶提供的數字),返回值:

>0 用戶提供的數字比隨機數大

=0 用戶提供的數字跟隨機數一樣大

<0 用戶提供的數字比隨機數小

(3)編寫一個測試方法,為用戶提供猜數字遊戲過程。

程序擴展一:每次猜數結果如果不對,則提示猜大了還是猜小了,最多可以猜10次。

程序擴展二:一次猜數結束,可以讓用戶選擇是繼續下一輪遊戲還是退出。

 1 package
ssj; 2 import java.util.Scanner; 3 import java.util.InputMismatchException; 4 public class Ssj { 5 //隨機數方法 6 public static int ssj1() { 7 int i = (int) (Math.random() * 1000); 8 System.out.println("產生的隨機數為"+i); 9 return i; 10 } 11 //返回值 12 public static int ssj2(int
x,int y) { 13 14 // TODO 自動生成的方法存根 15 16 if(x>y){ 17 return 1; 18 } 19 else if(x==y){ 20 return 0; 21 } 22 else 23 return (-1);
24 25 } 26 //遊戲 27 public static void main(String[] args){ 28 int count=0; 29 int min,max; 30 min=1; 31 max=1000; 32 int number=ssj1(); 33 34 while(count<10){ 35 Scanner sc = new Scanner(System.in); 36 System.out.println("請輸入你要猜的數字::(" + min + "~" + max + ")"); 37 38 try { 39 count++; 40 int guessNumber = sc.nextInt(); 41 // 判斷 42 int o=ssj2(guessNumber,number); 43 if (o==0) { 44 max = guessNumber; 45 System.out.println("你猜大了"); 46 // 問是否繼續 47 System.out.println("請問還要繼續嗎?(1代表繼續0代表結束)"); 48 sc = new Scanner(System.in); 49 // String str = sc.nextLine(); 50 int guessNumber1 = sc.nextInt(); 51 if (guessNumber1==1) { 52 53 } else { 54 break; 55 } 56 } else if (o==-1) { 57 min = guessNumber; 58 System.out.println("你猜小了"); 59 // 問是否繼續 60 System.out.println("請問還要繼續嗎?(1代表繼續0代表結束)"); 61 sc = new Scanner(System.in); 62 // String str = sc.nextLine(); 63 int guessNumber1 = sc.nextInt(); 64 if (guessNumber1==1) { 65 66 } else { 67 break; 68 } 69 } else { 70 System.out.println("恭喜你,花了" + count + "次就猜中了"); 71 // 問是否繼續 72 System.out.println("請問還要繼續嗎?(1代表繼續0代表結束)"); 73 sc = new Scanner(System.in); 74 // String str = sc.nextLine(); 75 int guessNumber1 = sc.nextInt(); 76 if (guessNumber1==1) { 77 // 重寫賦值隨機數 78 number = ssj1(); 79 count = 0; 80 max = 1000; 81 min = 1; 82 } else { 83 break; 84 } 85 } 86 87 }catch (InputMismatchException e) { 88 System.out.println("你輸入的數據有誤"); 89 90 } 91 92 } 93 } 94 }

猜數遊戲