java猜數字遊戲

利用NetBeans撰寫猜數字遊戲~~~

先由使用者從介面輸入欲猜測數字的範圍,

例如輸入30,則猜測範圍為0~30

電腦由這個範圍選出一個號碼當作正確答案,

使用者便開始猜,

若所猜的數字比正確答案小,

則電腦會提示小,反之

請大家幫忙一下~~謝謝~~

1 Answer

Rating
  • CK
    Lv 4
    1 decade ago
    Favorite Answer

    import java.util.Scanner;

    public class NumberGuessingGame2 {

    public NumberGuessingGame2() {

    int source = getNumber();

    String pattern = "^[-+]?[0-9]*\\.?[0-9]+$";

    System.out.print("Guess [0~30] type negative number to exit: ");

    Scanner scanner = new Scanner(System.in);

    String line = scanner.nextLine();

    boolean match=false;

    while(!match){

    if(line!=null && line.trim().length()>0 && line.matches(pattern)){

    int guess=Integer.valueOf(line);

    System.out.println("guess:"+guess);

    if(guess<0){

    match=true;

    System.out.println("Thank You!");

    }else {

    int result = matching(guess,source);

    switch(result){

    case 0:

    match=true;

    System.out.println("You Win!");

    break;

    case 1:

    System.out.print("Try smaller number: ");

    line=scanner.nextLine();

    break;

    case -1:

    System.out.print("Try bigger number: ");

    line=scanner.nextLine();

    break;

    }}} else {

    System.out.print("Try Again: ");

    line=scanner.nextLine();

    }}}

    private int getNumber() {

    return (int)(Math.random()*31);

    }

    private int matching(int guess, int source) {

    return (guess==source)?0:(guess>source)?1:-1;

    }

    public static void main(String[] args) {

    new NumberGuessingGame2();

    }}

    Source(s): Me
Still have questions? Get your answers by asking now.