天天看點

Java練習(1)- 猜數字遊戲

Java練習(1)- 猜數字遊戲

觀看學院老師java教程時,有個猜數字遊戲,自己也上手制作了一個。

package Test6;

import java.util.Scanner;

/**
 * @Author:Shilaiyuan
 * @Date:2020-10-29
 * @Description:猜數字遊戲,生成[0,100]之間的随機數,使用者猜生成的數字,傳回猜大猜小和猜對時的次數
 * @Email:[email protected]
 * */
public class NumRiddle {
    static int count;
    static int KeyNum;
    static boolean ComplexFlag;

    public static void main(String[] args){
        NumRiddle NR = new NumRiddle();
        while (true){
            count = 0;
            KeyNum = (int)(Math.random()*101);
            Scanner scanner = new Scanner(System.in);
            System.out.println("請輸入您猜的數字:");
            while (true){
                count ++;
                String str = scanner.next();
                //防止不規範輸入
                ComplexFlag = false;
                for (int i = str.length(); --i>=0 ; ){
                    int chr = str.charAt(i);
                    if(chr < 48 || chr > 57){
                        System.out.println("請輸入整數!");
                        count = 0 ;
                        ComplexFlag = true;
                        break;
                    }
                }
                if (ComplexFlag) continue;
                int InputNum = Integer.parseInt(str);
                if (InputNum < 0 ||InputNum > 100){
                    System.out.println("請輸入[0,100]之間的數!");
                    count = 0 ;
                    break;
                }


                if(NR.NumCompare(KeyNum, InputNum)){
                    System.out.println("恭喜你,猜對了!  " + "一共運作了" + count + "次");
                    count = 0 ;
                    break;
                }else if (NR.BigFlag(KeyNum,InputNum)){
                    System.out.println("猜小了");
                }else {
                    System.out.println("猜大了");
                }
            }
        }
    }

    /**
     * @Information:NumCompare比較兩數是否相同
     * @return :boolean
     * */
    public boolean NumCompare(int Num1, int Num2){
        boolean result = false;
        if (Num1 == Num2)
            result = true;
        return result;
    }

    /**
     * @Information:BigFlag傳回是否比原數大的結果
     * @return :boolean
     * */
    public boolean BigFlag(int Num1, int Num2){
        boolean result = false;
        if (Num1 > Num2) //
            result = true;
        return result;
    }
}

           

編寫說明:

1、添加輸入值檢測,輸入範圍以外的值報錯。

2、部分功能拆開從新編寫為函數

執行效果:

Java練習(1)- 猜數字遊戲

有問題歡迎給我留言|ू・ω・` )