Converting from int to byte forces an --- Exception in the main thread java.lang.NumberFormatException

I wrote a program for converting an IP address passed in strings to an IP address using a method InetAddress.getByAddress(byte[] addr).

So what I did was enter the IP address of the user as a String. Designed it and shared IP. using String.split("\\.").

Then I started converting this String array to an array of bytes, where I am stuck right now.

Please help me get rid of this situation. Any workaround OR alternative way to access this would be cordially appreciated ...

The code is as follows: -

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
0
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]);
    }
+1

All Articles