1. 程式人生 > >Java第三章上機實踐-實驗2-猜數字遊戲

Java第三章上機實踐-實驗2-猜數字遊戲



Guess.java

import java.util.Random;
import java.util.Scanner;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class Guess {
    public void guessnum(){
        Scanner reader=new Scanner(System.in);
        Random random=new Random();
        System.out.println("please input a number between 1 to 100:");
        int realNumber = random.nextInt(100)+1;  //隨機數字初始化
        int yourGuess = 0;
        System.out.println("please input the number which you guess:");
        yourGuess=reader.nextInt();
        //當yourGuess  的數字與隨機數不同時,進入while迴圈,直到兩數字大小一樣
        while(yourGuess!=realNumber){
            if(yourGuess>realNumber){
                System.out.println("your Guess number is bigger than real number,please input again:");
                yourGuess=reader.nextInt();
            }
            else if(yourGuess<realNumber){
                System.out.println("your Guess number is smaller than real number,please input again:");
                yourGuess=reader.nextInt();
            }
        }
        //輸出正確數字
        System.out.println("you are right!");
    }
}

Test.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class Test {
    public static void main(String[] aargs){
        Guess gu=new Guess();
        gu.guessnum();
    }
    
}