-2
package binarywa;
import java.util.*;

public class binaryadd {
    public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        String g=scan.next();
        String s[]=g.split("");
        int i,x=0;


        for(i=s.length;i>0;i--)
        {

         x+=Integer.parseInt(s[i])*Math.pow(2,i);
         }  

    }

}

Im trying to convert binary into decimal

but after compiling this im getting an arrayoutofbound exception

eg: 541656(its the input) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at binarywa.binaryadd.main(binaryadd.java:16)

4 Answers4

1

keep the length s.length-1 and i>=0 will print the first element as array index start from 0

package binarywa;
import java.util.*;

public class binaryadd {
    public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        String g=scan.next();
        String s[]=g.split("");
        int i,x=0;


        for(i=s.length-1;i>=0;i--)
        {

         x+=Integer.parseInt(s[i])*Math.pow(2,i);
         }  

    }

}
Roushan
  • 3,046
  • 3
  • 15
  • 31
0

the for loop conditions are incorrect. Array indices are accessible from 0 to (length - 1). This is the reason you are getting ArrayIndexOutOfBoundsException

for (i = s.length - 1; i >= 0; i--)
Onkar Kamatkar
  • 202
  • 2
  • 10
0

s.length in your code snipped will return 4.

In the loop you are trying to access s[4] which doesn't have a value. The s[] formed by g.split("") will have {1,2,3,4}

The indexes of these 4 array elements start with 0.

so,

s[0]=1
s[1]=2
s[2]=3
s[3]=4

once you try to access s[4] it will give ArrayIndexOutofBoundsException since at that index you don't have any value.

Solution is to run the loop as for(i=s.length-1;i>=0;i--)

Sudoss
  • 287
  • 1
  • 10
0

You need to change the for loop to as per the below

package binarywa;
import java.util.*;

public class binaryadd {
    public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        String g=scan.next();
        String s[]=g.split("");
        int i,x=0;


        for(i=s.length-1;i>=0;i--)
        {

         x+=Integer.parseInt(s[i])*Math.pow(2,i);
         }  

    }

}

But for that you also need to change your logic. i.e.

 x+=Integer.parseInt(s[i])*Math.pow(2,i+1);

else it will throw the NumberFormat Exception.