作者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)
1F:推 slalala:这 很正常啊 因为你这个变数是在while内宣告 03/05 00:57
2F:推 slalala:我会用Integer.parseInt(String str) 用Try catch去写这题 03/05 00:59