Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Error with OR operator

1. ## Error with OR operator

Hi, I know this is going to be SO simple when its pointed out but I've been working on this for the past 3 hours and I just can't understand it. I am VERY new to Java and I am trying to solve the 1st problem from project Euler. The problem is: To add all the natural numbers below 1000 that are divisable by 3 or 5. The following code determins whether the number is divisible by 3 and adds i to the total each time it finds a one. This part of the code works perfectly and I get the expected outcome. I can also change the value to 5 and that works accordingly.

class EulerFirstProject {
public static void main(String[] args) {

int total = 0;

for (int i = 0; i < 1000; i++) {
if (i % 3 != 0) {
continue;
}
total += i;
}

System.out.println(total);
}
}

So give that this works perfectly I figured I would just be able to add an OR operator to determine whether i is divisible by 3 OR 5:

class EulerFirstProject {
public static void main(String[] args) {

int total = 0;

for (int i = 0; i < 1000; i++) {
if ((i % 3 != 0) || (i % 5 != 0)) {
continue;
}
total += i;
}

System.out.println(total);
}
}

However for some reason this simply returns the value 49500. Witch is wrong. I have tried replacing 1000 with 10 which should give me a value of 23 but I get 0. Any pointers would be hugely appreciated.

Thanks

2. ## Re: Error with OR operator

To figure out how to write the conditions correctly, write a small simple program with a loop with the if test inside. Add printlns to show when the conditions are true and when they are not and to show the value of i for both those cases.

3. ## Re: Error with OR operator

Ohhhhhhhhh, I can't beleive it... I'm so simple!!! Thanks very much for the quick feedback. I'm so sorry for such a stupid post

4. ## Re: Error with OR operator

No problem. Lots of programmers have problems with != and || together.
A quick short program to printout what is happening and the light comes on.