# 請各位幫我想想JAVA猜數字程式(15點)

### 1 個解答

• 匿名使用者
2 0 年前
最佳解答

//猜數字

import java.io.*;

public class guess

{

private static short cpu[] = new short[4];

private static short player[] = new short[4];

private static boolean num[] = new boolean[10];

private static short i,j,k,temp,round,a,b,str_length;

private static final short MAX_ROUND = 10;

private static boolean ok = true;

//亂數取0~n-1的值

public static short rand(short n){

short temp;

do{

temp = (short)(Math.random() * 10);

}while(temp > n);

return temp;

}

//印出陣列

public static void show(short a[]){

for(int i = 0; i < a.length; i ++)

System.out.print(a[i]);

}

public static void main(String args[])throws IOException

{

String str = "0000";

//用來記憶電腦取過的數字

for(int d = 0; d < 10; d ++){

num[d] = false;

}

//亂數取4個不重複的數字

i = 0;

do{

do{

j = rand((short)10);

}while(num[j] == true);

num[j] = true;

cpu[i] = j;

i++;

}while(i < 4);

System.out.println("最多猜" + MAX_ROUND + "次\n");

round = 1;

do{

try{

System.out.print("請輸入4位數->");

str_length = (short)str.length();

if(str_length != 4){

System.out.println("\n數值超過(不足)，請重新輸入!\n");

continue;

}

temp = Short.parseShort(str);

//把輸入的4位數一一存放到陣列中

for(k = 3; k >= 0; k--){

player[k] = (short)(temp % 10);

temp /= 10;

}

}catch(NumberFormatException e){

System.out.println("數值格式不對，請重新輸入!\n");

continue;

}finally{

temp = 0;

}

//判斷輸入的數值是否有重複

for(int d = 0; d < 4; d++){

for(int e = d + 1; e < 4; e++){

if(player[d] == player[e])

ok = false;

}

}

//如果輸入不正確，要重新再輸入一次

if(ok == false){

System.out.println("\n數值重複，請重新輸入!\n");

ok = true;

for(int i = 0 ;i < 4; i++)

player[i] = 0;

continue;

//如果輸入正確，就判斷?A?B

}else if(ok == true){

System.out.print("\n" + round + " round...");

round ++;

show(player);

for(int i = 0; i < 4; i++){

for(int j = 0; j < 4; j++){

//數字對，位置也一樣，就是1A

if((player[i] == cpu[j]) && (i == j))a++;

//數字對，位置不一樣，就是1B

else if((player[i] == cpu[j]) && i != j)b++;

}

}

}

System.out.println(" " + a + "A" + b + "B\n");

if(a == 4){

System.out.println("你猜中了!!");

break;

}

a = 0;

b = 0;

}while(round <= MAX_ROUND);

if(round > MAX_ROUND)System.out.print("超過" + MAX_ROUND + "回合!!");

System.out.print("答案是");

show(cpu);

System.out.println();

}

}

//以上為程式碼

//------------------------------------------------------------

變數MAX_ROUND是用來限制能猜幾回合的，我設定是10回合，程式碼檔案你可以到我的網站下戴，下面參考資料就是我的網站…