Errors with some basic while and for loops, help?
Hello. For a class assignment, I have to write a program that finds the first four perfect numbers on the domain (0, ∞). A perfect number is a number that has the sum of its divisors (aside from the number itself) equivalent to the number. 6, for example, is a perfect number.
Anyways, here's my code.
Code:
public class PerfectNumbers
{
public static void main(String[] args)
{
int i = 1;
while (int i <= 4)
{
int j;
for (int j = 1; i <= 4; j++;)
{
int sum = 0;
int k = 1;
while (k <= j - 1)
{
if (j % k == 0)
{
sum += k;
k++;
}
else
k++;
}
if (sum == j)
{
System.out.println(j);
i++;
}
}
}
}
}
I'm getting errors on lines 7, 10 and 33. I'm sure I'm making some novice mistakes...can someone please point me in the right direction?
Thank you.
Re: Errors with some basic while and for loops, help?
When you get errors you should post the exact error message.
Computers are very good at remembering things. Once you have told the computer what type a variable is you do not have to keep reminding it.
Re: Errors with some basic while and for loops, help?
Oh, hey, taking out the two extra "int"s fixed most of my errors! Thank you.
Now I'm left with two. Seems to be a problem with my for loop.
On line 10, I'm getting a "')' expected" and "illegal start of expression"
Re: Errors with some basic while and for loops, help?
Look very carefully on that line to see if anything that should be there isn't or if anything that is there shouldn't be there.
Re: Errors with some basic while and for loops, help?
Re: Errors with some basic while and for loops, help?
Thanks a lot guys. We just learned how to write for and while loops today in class, so I'm glad it was only a small syntax error.
Now I just have to figure out why my program isn't printing anything. But I guess that's just a logic error...at least the compiler errors are gone. Thanks again.
Re: Errors with some basic while and for loops, help?
Sorry for the double post, but I got my program working. Whoo! When I went back to edit it I had changed one of the less than signs to greater than. All is well now.
Re: Errors with some basic while and for loops, help?
This can be achieved with only 2 loops. The outer loop goes until it finds the four perfect numbers. The inner loop calculates all the factors of a given number and sums them. After the inner loop have an if statement to see if the sum equals the number.