比如在程序中有个方法要接受该参数进行运算,如果输入的是任意数,则可用Integer.parseInt(args[0])转换,如果是“abcd、4t56”等类的字母或其他符号则不接受参数。代码因该怎么写?

解决方案 »

  1.   

    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);
    }
    }
      

  2.   

    boolean b = false;
    try{
       int i =Integer.parseInt(args[0]);
    }
    catch(Exception e){
       b=true;
    }
    if(b){
      System.out.println("输入有错,请输入一个整数");
    }
      

  3.   

    参考 commons-util 里面的StringUtils类