作者divaka (豬肉腳)
看板java
標題[問題] 讀入字串判斷是否為數字的問題
時間Wed Mar 5 00:50:42 2008
大家好,小弟目前已經可以成功讀入字串並且判斷是否為數字,部份的 code 如下
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String price = (String) buf.readLine();
char[] price_array = price.toCharArray();
for(int index=0; index < price.length(); index++) {
if(!Character.isDigit(price_array[index])) {
System.out.println("您不是輸入數字");
break;
}
}
這樣子還不會出錯,但我希望加上「如果不是輸入數字就請重新輸入的功能」所以我加上
boolean num =false;
while(num==false)
{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String price = (String) buf.readLine();
char[] price_array = price.toCharArray();
for(int index=0; index < price.length(); index++) {
if(!Character.isDigit(price_array[index])) {
System.out.println("您不是輸入數字");
break;
}
else
{
num =true; //表示使用者正確輸入了數字
}
}
}
用意是只有當使用者輸入數字後,會把 num 布林變數改成 true ,就會跳出 while迴圈
但程式就顯示 cannot find symbol "variable price"
意思是在 while 迴圈的括號以外其他地方找不到 price 這個變數了...
請問為什麼呢?
謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
※ 編輯: divaka 來自: 140.123.175.240 (03/05 00:52)
推 slalala:這 很正常啊 因為你這個變數是在while內宣告 03/05 00:57
推 slalala:我會用Integer.parseInt(String str) 用Try catch去寫這題 03/05 00:59