请问,在运行JAVA类时输入参数,怎样判断输入的参数是“数字型”的字符串还是“字母或其他类型”的字符串?
比如在程序中有个方法要接受该参数进行运算,如果输入的是任意数,则可用Integer.parseInt(args[0])转换,如果是“abcd、4t56”等类的字母或其他符号则不接受参数。代码因该怎么写? 问题点数:20、回复次数:4Top
1 楼superslash(开始用功学习)回复于 2006-05-02 08:57:23 得分 0
throw ExceptionTop
2 楼tomison()回复于 2006-05-02 13:08:18 得分 0
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class GetInt
{
public int getInt()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
String str=br.readLine();
if(str.length()==0)
return -1;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)<'0'||str.charAt(i)>'9')
return -1;
}
return Integer.parseInt(str);
}
catch(IOException e)
{
System.out.println("输入有错!");
return -1;
}
}
}
class Input
{
public static void main(String[] args)
{
GetInt get=new GetInt();
System.out.println("输入一个整数");
int num=get.getInt();
while(num==-1)
{
System.out.println("输入有错,请输入一个整数");
num=get.getInt();
}
System.out.println(num);
}
}Top
3 楼zt_soft(Get busy living, Or get busy dying.)回复于 2006-05-02 14:10:56 得分 0
boolean b = false;
try{
int i =Integer.parseInt(args[0]);
}
catch(Exception e){
b=true;
}
if(b){
System.out.println("输入有错,请输入一个整数");
}Top
4 楼YidingHe(机枪兵)回复于 2006-05-02 15:42:19 得分 0
参考 commons-util 里面的StringUtils类Top




