-2

Good afternoon! I have to create 2 arrays. 1st one should create a random number (-10;10) if a user write 0, otherwise it should count using an entered formula; the 2nd array should write firstly elements from an array1 which have uneven number of position and then even number of position. So basically in the array2 0-10 positions for uneven numbers and then 11-19 positions for even. But unfortunately when I "run" the program 2nd array has an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20).

int K;  
System.out.print("K=");
if (sc.hasNextInt())
    K=sc.nextInt();
else {
    System.out.println("Error (is not an integer)");
    sc.close();
    return;
}

double A[]=new double [20];
double B[]=new double [20];

System.out.println ("result:");
System.out.println ("A: ");
if (K==0) {
    Random r=new Random();
    for (int i=0; i<20;i++) {
        A[i]=-10+20*r.nextDouble();
    }
}
if (K!=0) {
    A[0]=1;
    for (int i=1;i<20;i++) { 
        double a=Math.sin(A[i-1])*K; 
        A[i] = Math.round(a * 100.0) / 100.0;
    }
}

int i=0;
while (i<20) { 
    System.out.printf("%.2f", A[i]); System.out.print(" ");
    if (i==9) System.out.println();
    i++;
}

System.out.println ();
System.out.println ("B: ");
int even=11, uneven=0, p=0;
do { 
    int z=p;
    if (z%2==0) {
        B[even]=A[p];
        even++;
    }
    if (z%2!=0) {
        B[uneven]=A[p];
        uneven++;
    }
    p++;
} while (p<20);

for (int k=0; k<20;k++) { 
    System.out.printf ("%.2f",B[k]); System.out.print(" ");
    if (k==9) System.out.println();
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
Eli
  • 51
  • 5

2 Answers2

0

In the do-while loop:

p=0 -> p is even, 'even' get incremented and become 12.
p=2 -> p is even, 'even' get incremented and become 13.
...
p=14 -> p is even, 'even' get incremented and become 19.
p=16 -> p is even, 'even' get incremented and become 20. <- game over!

Is there an easy fix?

Divide all integers below 20 by 2 and you get:

0/2 = 0
1/2 = 0
2/2 = 1
3/2 = 1
4/2 = 2
...
18/2 = 9
19/2 = 9

You see the pattern?

The new index should be 10+(p/2)for even pand p/2 for odd p

    do { 
        if (p%2==0) { //p is even
            B[10+(p/2)]=A[p];
        }
        if (p%2!=0) { //p is odd
            B[(p/2)]=A[p];
        }
        p++;
    } while (p<20);
jhamon
  • 3,603
  • 4
  • 26
  • 37
0

Make the following changes, your code will be good to Run,

double B[ ] = new double[ 21 ];

do
      {
         int z = p;
         if (z % 2 == 0)
         {
            B[even] = A[p];
            even++;
         }
         else
         {
            B[uneven] = A[p];
            uneven++;
         }
         p++;
      }
      while (p < 19);

Notice the condition inside while.

by the way, you don't need to introduce z inside the loop, it's useless, just replace z by p in the if condition.

if (p % 2 == 0)
User_67128
  • 1,230
  • 8
  • 21