Warm tip: This article is reproduced from serverfault.com, please click

why can't my java code read the condition?

发布于 2020-11-28 19:00:34

what I attend to do is when the array(from 0 to n-1) is given, to sum the array values with the index minus multiple of 3 start from the end. for example, when 7 arrays are given, I want to sum a[0] a[2] a[3] a[5] a[6].

below is error part of the code I programmed.

        int j = 0;

        for(int i=0; i<n; i++){
                j = i*3;

                if(i!=n-j)
                        r += array[i];
        }

my code can't read the condition and just sum all the array values. I don't know why. can someone help me ?

Questioner
Sexy No.1
Viewed
0
rzwitserloot 2020-11-29 03:07:53

Let's debug!

first time through the loop:

i = 0 j = i * 3 soo... 0 if (0 != 7 - 0) ... - it's not, of course, so i = 0 qualifies and is added.

next loop:

i = 1 j = 3

if (1 != 7 - 3) ... - it's not, of course, so i = 1 qualifies and is added.

Which you did not want.

Given that this is homework, this should be enough for you to take another step and figure out what you SHOULD be doing here. I will give some tips:

You can loop, counting backwards, just as well. You'd have to use i-- of course (decrement i by 1 every time), and you'd use int i = n or perhaps int i = n - 1 as initializing expression in your for loop.

That whole 'is it a 3rd factor from the top' part cannot be calculated using i at all, you'd need something separate for this. You can declare variables outside (you already did that, int j = 0, but you're not looking for 0 so much as 'the first index from the top I do not want'. Then you can use if to check if it is that index. If so, you don't want to add that number to your sum AND you want to update your j.