If you are accepting integers simultaneously one after another for a different array each time an int is accepted, then how do you form a third array with the digits of the 2 other arrays in the order in which they are accepted?
import java.util.Scanner;
class Integer_Acceptor
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i )
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
for (int i = 0; i < 10; i )
{
if (i%2 != 0)
{
c[i] = a[i];
c[i 1] = b[i];
}
}
System.out.println("Array contents are");
for (int i = 0; i < 10; i )
{
System.out.println(c[i] "\t");
}
}
}
This is the program I made but obviously it doesn't work (ArrayOutofBounds) as the integer in array increases by 2 every time. How do I make this program give the combined integers of both arrays in the order in which they are accepted?
CodePudding user response:
The code you provided will give an ArrayOutofBounds error as you mentioned because c[10] does not exist. (In the second for loop when i = 9, you will be trying to set c[10] which does not exist).
From what I understand, you want array c to contain the following elements:
c = { a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3], a[4], b[4] }
What I did was to create two separate indices that will help navigate through array a and array b and set c[i] according to whether i was even or odd and then incrementing the respective aIndex or bIndex. I wrote this code below that works the way I described
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i )
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
// Fixed code snipped
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < 10; i )
{
// even index
if(i%2 == 0){
c[i] = a[aIndex];
aIndex ;
}
else
{
c[i] = b[bIndex];
bIndex ;
}
}
////
System.out.println("Array contents are");
for (int i = 0; i < 10; i )
{
System.out.println(c[i] "\t");
}
Let me know if you need further clarification on how this works so I can edit in a more in-depth explanation.
CodePudding user response:
The idea of separating the inputs is interesting, but it seems to be giving you more problems than solutions when trying to join them together later.
Why not just accept everything into a single array, and when reading it, you test its index to see where it should go? If you have two possible uses for your numbers, odd and even positions will get you there; if three, multiples of 3 plus or minus one, and so on.
This seems to be a simpler solution, and both the input and data storage are as straightforward as can be.