【问题标题】:Conversion from int to byte forcibly results in --- Exception in thread "main" java.lang.NumberFormatException从 int 强制转换为 byte 会导致 --- 线程“main”java.lang.NumberFormatException 中的异常
【发布时间】:2014-11-15 18:33:27
【问题描述】:

我正在编写一个程序,利用InetAddress.getByAddress(byte[] addr) 方法将字符串馈送的IP 地址转换为IP 地址。

所以,我所做的就是以字符串的形式输入来自用户的 IP。解析它并在 .使用String.split("\\.")

然后,我开始将该字符串数组转换为我现在卡住的字节数组。

请帮助我摆脱这种情况。任何解决方法或访问它的替代方式将不胜感激......

代码如下:-

public static void main(String[] args) {
    try{
        System.out.println("Enter the IP-Address whose MAC-address you wanna know :-");
        Scanner s=new Scanner(System.in);
        String ipa=s.nextLine();
        String ba[]=ipa.split("\\.");
        for(String ap:ba){
            System.out.println("Given IP="+ap);
        }
        byte [] bad=new byte[ba.length]; 
        for(int i=0;i<ba.length;i++){
            System.out.println("Ba-"+i+"="+ba[i]);
        if(Integer.valueOf(ba[i])>127){
            int temp=Integer.valueOf(ba[i]);
            //System.out.println("Value of "+i+"---"+temp);
            bad[i]=(byte) temp;    // this produces error at run-time
        }
            bad[i]=Byte.valueOf(ba[i]);
            System.out.println("Bad-"+i+"="+bad[i]);
        }
        //byte bad[]={(byte)192,(byte)168,122,1};
        InetAddress ia=InetAddress.getByAddress(bad);
        ...............  here is the rest of code and it compiles well.

抛出异常:-

Enter the IP-Address whose MAC-address you wanna know :-
192.168.122.1
Given IP=192
Given IP=168
Given IP=122
Given IP=1
Ba-0=192

Exception in thread "main" java.lang.NumberFormatException: Value out of range.   Value:"192" Radix:10
at java.lang.Byte.parseByte(Byte.java:151)
at java.lang.Byte.valueOf(Byte.java:205)
at java.lang.Byte.valueOf(Byte.java:231)
at NP_7.main(NP_7.java:36)
Java Result: 1

【问题讨论】:

  • 我想知道谁否决了这个问题,因为我没有得到我需要的确切解决方案!

标签: java network-programming bytearray arrays numberformatexception


【解决方案1】:

如果您改用InetAddress.getByName(String),您可以避免所有这些麻烦。

您收到错误是因为字节的范围是从 -128 到 127,例如 192 超出范围。

您可以通过将填充bad 的循环更改为以下代码来修复代码:

    for(int i=0;i<ba.length;i++){
        System.out.println("Ba-"+i+"="+ba[i]);
        bad[i] = (byte) Integer.parseInt(ba[i]);
    }

【讨论】:

  • getByName 接受 IP 地址,而不仅仅是主机名。
  • 好吧,如果你真的要自己解析IP地址,代码不难修复,看更新...
  • 再次抛出异常---不兼容的类型,Integer 无法转换为byte。您的代码虽然不正确且不可编译,但是您的建议对我有所帮助!所以,我接受你的回答。请删除fixing code section,以便我投票并接受答案...
  • 你确定你的代码正是我发布的吗? parseInt 方法返回一个原始 int,而不是一个 Integer 对象,所以我看不出你怎么会得到那个错误。
  • 我很困惑,所以请认为这句话有意义,实际上,当我按照您的代码建议这样做时,它又开始给出问题的原始异常---bad[i]=(byte)Integer.parseInt(ba[i]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
相关资源
最近更新 更多