[問題] 讀入字串判斷是否為數字的問題

看板java作者 (豬肉腳)時間18年前 (2008/03/05 00:50), 編輯推噓2(200)
留言2則, 1人參與, 最新討論串1/6 (看更多)
大家好,小弟目前已經可以成功讀入字串並且判斷是否為數字,部份的 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)

03/05 00:57, , 1F
這 很正常啊 因為你這個變數是在while內宣告
03/05 00:57, 1F

03/05 00:59, , 2F
我會用Integer.parseInt(String str) 用Try catch去寫這題
03/05 00:59, 2F
文章代碼(AID): #17pNtZTV (java)
討論串 (同標題文章)
文章代碼(AID): #17pNtZTV (java)