Conversion from int to byte forcibly results in — Exception in thread “main” java.lang.NumberFormatException

不问归期 提交于 2019-12-25 01:17:42

问题


I was writing a program to convert a String fed IP-Address to IP-Address by utilising the method InetAddress.getByAddress(byte[] addr).

So, what I did was input IP-from the user in the form of String. Parsed it and splitted the IP on . using String.split("\\.").

Then, I started converting that String array into byte array where I am right now stuck on.

Please help me to get rid of this situation. Any workaround OR alternate way of accessing this will be heartly appreciated...

The code goes as :-

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.

Exception thrown :-

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

回答1:


You can save yourself from all this trouble if you use InetAddress.getByName(String) instead.

You get the error because the range of byte is from -128 to 127, so for example 192 is out of range.

You can fix the code by changing the loop that fills bad into this:

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


来源:https://stackoverflow.com/questions/26949268/conversion-from-int-to-byte-forcibly-results-in-exception-in-thread-main-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!