题目是:编写程序,接受使用命令行参数输入的数字,并计算它的字节数。此程序应在数字超出字节范围时引发用户自定义异常。如果输入的是字母而非数字,也应捕获错误并显示错误消息。
请高手帮看看小弟写的程序错在哪里?class TestException
{
public static void main(String[] args)
{


try{
int a=Integer.parseInt(args[0]);
if(args.length>5){
throw new MyException();
}else{
System.out.println(a+"的字节长为: "+args.length);
}
}catch(MyException me){
System.out.println("输入范围错误!");
}catch(NumberFormatException ne){
System.out.println("输入数据类型错误!");
}
}
}class MyException extends Exception
{
MyException()
{
System.out.println("超出输入范围!");
}
}

解决方案 »

  1.   

    args是个数组,if(args.length>5)表示你输入的参数个数大于5。如果你要测第一个参数的长度大于5应是if(args[0].length()>5)
      

  2.   

    class Test
    { public static void main(String[] args) { try{
    int a=Integer.parseInt(args[0]);
    if(args[0].length()>5){
    throw new MyException();
    }else{
    System.out.println(a+"的字节长为: "+args[0].length());
    }
    }catch(MyException me){
    System.out.println("输入范围错误!");
    }catch(NumberFormatException ne){
    System.out.println("输入数据类型错误!");
    }
    }
    }class MyException extends Exception
    {
    MyException()
    {
    System.out.println("超出输入范围!");
    }
    }
      

  3.   

    catch(MyException me){
    System.out.println("输入范围错误!");
    }catch(NumberFormatException ne){
    System.out.println("输入数据类型错误!");
    NumberFormatException 不是MyException 的父类,不能捕获此异常