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)
int i = 0;binaryFormhas no reason to returnObjectso its return type should bevoid, or perhapsString(if you wanted the binary returned instead of printed).