Hello,
I was hoping to get some input from anyone in the Java section. My professor gave us a practice problem about two weeks ago and I have been running into an out of bounds error. The program seemed simple enough, take in two arrays of binary numbers from a user, add them, and return the sum as a third array.
So far I have this:
import java.util.*;
public class Binary
{
public static int[] calculate(int[] arr1, int[] arr2)
{
int length = (arr1.length + arr2.length);
int carry = 0;
int[] newArray = new int[length];
for(int i = 0; i < newArray.length; i++)
{
if((arr1[i] == 1) && (arr2[i] == 1))
{
newArray[i] = 0;
carry = 1;
}
if((arr1[i] == 1) && (arr2[i] == 1) && carry == 1)
{
newArray[i] = 1;
carry = 1;
}
if((arr1[i] == 1) && (arr2[i] == 0))
{
newArray[i] = 1;
}
if((arr2[i] == 1) && (arr1[i] == 0))
{
newArray[i] = 1;
}
}
return newArray;
}
public static boolean isValid(int val)
{
if(val == 0 || val == 1)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int length, length2;
System.out.print("Enter a length for array 1: ");
length = keyboard.nextInt();
//First Array
int[] array1 = new int[length];
int temp;
int counter = 0;
System.out.print("Please enter 1 or 0 to represent a binary value\n"
+"--------------------------------------------------\n");
while(counter < array1.length)
{
System.out.print("#"+(counter+1)+":");
temp = keyboard.nextInt();
if(isValid(temp) == true)
{
array1[counter] = temp;
counter++;
}
else
System.out.print("Incorrect value. Try again: ");
}
counter = 0;
System.out.print("Array #1: ");
for(int i = 0; i < array1.length; i++)
System.out.print(array1[i]+" ");
System.out.println();
//Second Array
System.out.print("Enter a length for array 2: ");
length2 = keyboard.nextInt();
int[] array2 = new int[length2];
System.out.print("Please enter 1 or 0 to represent a binary value\n"
+"--------------------------------------------------\n");
while(counter < array2.length)
{
System.out.print("#"+(counter+1)+":");
temp = keyboard.nextInt();
if(isValid(temp) == true)
{
array2[counter] = temp;
counter++;
}
else
System.out.print("Incorrect value. Try again: ");
}
counter = 0;
System.out.print("Array #2: ");
for(int i = 0; i < array2.length; i++)
System.out.print(array2[i]+" ");
System.out.println();
//Third Array (sum of array1 and array2)
int[] array3 = calculate(array1, array2);
for(int i = 0; i < array3.length; i++)
System.out.print(array3[i]+" ");
}
}
But, I seem to run in to an array out of bounds error. I thought if I set the length to the sum of both array 1 and array 2 it would suffice. Also, instead of if-statements what are other suggestions to make this program more efficient?