Reputation: 649
i am new in java coming from c++ and C. when i pass simply arr= 4 gives correct ouptput but when i pass arr[i]=4 it gives error. could someone tell me and correct me?
code :
package GA;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number = 0;
int i=1;
int[]arr = new int[]{4};
// arr[i]4;
// number=arr[i];
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(arr[i])); // error occuring
}
}
private static Object binaryform(int arr) {
int remainder;
if (arr <=1) {
System.out.print(arr);
return null; // KICK OUT OF THE RECURSION
}
remainder= arr %2;
binaryform(arr >>1);
System.out.print(remainder);
return "";
}
}
error:
Convert to binary is:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GA.ReversedBinary.main(ReversedBinary.java:18)
Upvotes: 0
Views: 59
Reputation: 1136
ur array arr[] has only 1 element in it
and ur value of i is 1
u are passing arr[1] to the method which doesn't exist for ur array arr.
When u are doing arr = 4 , it means u are assigning 4 to the arr[0].
When u had declared
int[] arr = new int[]{4}, u have pushed and fixed only 1 element in the array arr.
so,
u cant push or assign any value to arr[1] , because it is not in array / cant be pushed in array.
Try changing it as ,
int arraysize = //some integer value
int[] arr = new int[arraysize]
, note : arraysize is some int value which is the maximum element ur array can have.
or change the value of i ,
int i = 0;
Upvotes: 1
Reputation: 1327
In Java, array indexes start at 0 :
int[] array = new int[]{4};
boolean valid = array[0] == 4; // Valid
boolean invalid = array[1] == 4; // Invalid
So what you need to do is initialize i with the value 0.
Upvotes: 2
Reputation: 931
public class ReversedBinary {
public static void main(String[] args) {
int number = 0;
int i=0; // i is initialized to zero
int[]arr = new int[]{4};
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(arr[i])); // error occuring
}
}
private static Object binaryform(int arr) {
int remainder;
if (arr <=1) {
System.out.print(arr);
return null; // KICK OUT OF THE RECURSION
}
remainder= arr %2;
binaryform(arr >>1);
System.out.print(remainder);
return "";
}
}
Try this.
Upvotes: 1