Reputation: 1
I'm new in Java
, it's my first attempt to write a program:
I need to write a program that prints the sum of all positive integers smaller
than 1000, that are divided by either 3 or 5.
Here is my (poorly) attempt. after compiling it is just receiving numbers and showing them :
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int num=1;
int count = 1;
while (count <=1000) {
if (count%3==0|count%5==0){
count = count+num;
count++;
}
}
System.out.println(count);
}
}
Upvotes: 0
Views: 97
Reputation: 11153
You have put your count++
inside if block. That means if the number is divisible by 3 or 5 then you are incrementing the count
. Place it outside of your if block. I have re-write your code as follows -
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int sum = 0;
int count = 1;
while (count <=1000) {
if (count%3==0||count%5==0){
sum = sum + count;
}
count++;
}
System.out.println(sum);
}
}
Upvotes: 0
Reputation: 4652
Given you used a while, I assume you don't know about for loops, so I'll avoid using it.
Your code should:
Point 1):
int sum = 0;
Point 2):
int value = 1;
while (value <= 1000) {
//do point 3
value++;
}
Point 3):
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
Point 4):
System.out.println(sum);
Putting it all together:
int sum = 0;
int value = 1;
while (value <= 1000) {
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
value++;
}
System.out.println(sum);
Your main error is in using count both for the sum and for the value check of the while condition. The misusage of the single pipe as or is also a mistake.
Hope this helps
Upvotes: 3
Reputation: 248
public class Test {
public static void main(String[] args) {
int num=1;
int sum=0;
while (num <=1000) {
if (num%3==0||num%5==0){
sum = sum +num;
}
num++;
}
System.out.println(sum);
}
}
Upvotes: 1