[問題] 關於終極密碼程式
/*
我是個初學者,所以不會的地方還很多,請各位高手多多指教,以下是我的寫法:
*/
import java.io.*;
import java.util.Random;
public class test01 {
public static void main(String[] args) throws IOException {
int num, min, max;
max = 100;
min = 0;
Random ran = new Random();
int m = 100;
int temp = 0;
temp = ran.nextInt(m)+1;
System.out.println("temp = " + temp);
boolean find = false;
System.out.println("(1~100)");
System.out.print("→");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
num = Integer.parseInt(str); //num = 輸入的值
do{
int num2;
if (num<temp){ //輸入的值若小於系統產生的隨機數字
min = num;
System.out.print(num + "to" + max + ":");
System.out.print("→");
String str2 = br.readLine();
num2 = Integer.parseInt(str2);
num = num2;
find = false;
}
else if(num>temp){ //輸入的值若大於系統產生的隨機數字
max = num;
System.out.print(min + "to" + num + ":");
System.out.print("→");
String str2 = br.readLine();
num2 = Integer.parseInt(str2);
num = num2;
find = false;
}
else if(num == temp){
find = true;
break;
}
}while(find == false);
}
}
/*
我先讓temp顯示出來測試一下,等到都沒問題之後再拿掉。
我寫出來之後會出現一個問題..
temp = 31
(1~100)
→50
0to50:→25
Press any key to continue...
也就是說,當我進入do..while迴圈之後,輸入第二次的數字它就不會再跑do..while迴圈
了...我要怎麼樣才可以讓它一直在do..while迴圈內跑到num=temp才離開迴圈呢?
*/
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.60.110.98
推
03/10 10:09, , 1F
03/10 10:09, 1F
→
03/10 11:00, , 2F
03/10 11:00, 2F
我已經改過程式了,但是它範圍會擴展= =
執行結果:
temp = 39
(1~100)
→50
0to50:→20
20to50:→90
20to90:→10
10to90:→_
照理說...
當20to50時,我輸入的num超過這個範圍程式可能會出錯,但它會自己擴展成20to90..囧
如果我要去判斷num是否小於min或num是否大於max應該加在哪裡好呢?
※ 編輯: IC2You 來自: 61.60.110.98 (03/10 11:25)
→
03/10 11:32, , 3F
03/10 11:32, 3F
→
03/10 11:56, , 4F
03/10 11:56, 4F
推
03/10 12:38, , 5F
03/10 12:38, 5F
→
03/10 12:47, , 6F
03/10 12:47, 6F
→
03/10 12:47, , 7F
03/10 12:47, 7F
→
03/10 13:00, , 8F
03/10 13:00, 8F
→
03/10 13:07, , 9F
03/10 13:07, 9F
如同影片所示,一開始我讓程式隨機抓一個數字,假設是33,遊戲開始:(temp=33)
一開始最大值是100,最小值是0 (max = 100; min = 0;)
如果我猜50,那麼程式就就會幫我把範圍縮小,33介於0到50之間 (num>temp)
那麼程式就會show出0to50,再繼續跑這個迴圈
直到猜到33(num=temp)為止...
但假設現在已經縮小範圍為0to50了
但我又去猜非這個範圍內的數字,比如說75
但程式會顯示0to75
而我希望程式會以System.out.println告訴我超過範圍並且要我重新輸入
所以到底應該改哪裡呢...
※ 編輯: IC2You 來自: 61.60.110.98 (03/10 13:41)
→
03/10 13:53, , 10F
03/10 13:53, 10F
→
03/10 14:13, , 11F
03/10 14:13, 11F
→
03/10 14:15, , 12F
03/10 14:15, 12F
→
03/10 14:41, , 13F
03/10 14:41, 13F
→
03/10 14:44, , 14F
03/10 14:44, 14F
→
03/10 14:47, , 15F
03/10 14:47, 15F
→
03/10 14:49, , 16F
03/10 14:49, 16F