0

This is for my AP Computer Programming class and I am lost at whats wrong with my code. My other programming teacher basically sees nothing wrong with my code and I've tried various different sets of code to work, but none have. This code, however seems the most likely to work.

int[] d = {8, 7, 6, 2 }; 
boolean valid;

int sum = 0;
int dd;

for ( int i = 0; i < d.length; i++ )
{

    if ((d[d.length - i] %10) == 0 )
    {
        dd = d[d.length - i] * d[d.length - 1];
        sum += dd ;
   }
   else
   {
        sum += d[d.length - i] ;
   } 
}
 
   if ( sum %10 == 0)
{ 
valid = true;
}
else 
{
   valid = false;
}

What am I doing wrong. Here's the error that is coming up

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

at TC1.work(TC1.java:24)

at TC1.main(TC1.java:12)

  • The first rule of troubleshooting problems like this is to single-step the program in an IDE debugger. You will learn how the program is actually behaving, and the problem will be obvious. – Jim Garrison Oct 22 '14 at 14:51

3 Answers3

0

Here's the crux of the problem:

if ((d[d.length - i] %10) == 0 )

When i is 0, then d.length - 0 is 4. d[4] is, indeed, out of bounds.

To fix this, you can also subtract 1 from d.length, like so:

if ((d[d.length - i - 1] % 10) == 0)
  • When i = 0 (lowest value in for-loop), d[3] is valid
  • When i = 3 (highest value in for-loop), d[0] is valid

Keep in mind that d[d.length - i] appears in a few different places in your code; make sure to correct each occurence.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • That is almost exactly what I did. I realized what I was doing wrong, after speaking with my teacher for a little bit and came up with my answer I just posteed – Edragongaming Oct 22 '14 at 15:06
0

d[d.length - i]

At all cases when i = 0 you will get this error since arrays start at 0 and go up to array.length - 1

You can correct this by doing d[d.length - i - 1]

Luminous
  • 1,771
  • 2
  • 24
  • 43
0
 int[] d = {8,7,6,2  }; 
   boolean valid;
int sum = 0;
int dd;

for ( int i = 0; i < d.length; i++ )
{

  if ((d.length - i) %2 == 0 )
  {
    dd = d[i] * 2;

  }
  else
  {
    sum += d[i] ;
  } 
  }
 
if ( sum %10 == 0)
{ 
    valid = true;
}
else 
{
    valid = false;
}

Ok so I retried the code with slightly different inputs and well it worked