A problem with my 'perfect numbers' Applet
I have written the following applet to cycle through 1000 integers and to determine whether or not each is a perfect number (ie. equal to the sum of it's divisors - such as 6 = 1 + 2 + 3).
I used the same mathematics in a previous applet in which the user could enter any number and the applet would tell the user whether or not the number is perfect. That applet worked perfectly.
For some reason, when I used the same method in the new applet, it returns an answer saying that every number after 1 is NOT a perfect number.
Does anybody have any idea what I am doing wrong?
(P.S. I hope the formatting is ok. I know I posted some code yesterday which did not observe the posting rules.)
//Coded by Eoghain on 28/5/07
//A program to check perfect numbers
//Third attempt!
//This nearly works!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass PerfectNumberCheck2extends JApplet
{
int numberToCheck, sumOfDivisors, sumSoFar;
JTextArea outputArea;
JScrollPane scroller;
publicvoid init()
{
//set up GUI
Container container = getContentPane();
container.setLayout(new FlowLayout());
outputArea =new JTextArea(20, 30);
scroller =new JScrollPane(outputArea);
container.add(scroller);
}
publicvoid start()
{
//Cycle through every integer from 1 to 1000
//and check to see if each is a perfect number
for (int i = 0; i <= 1000; i++)
{
numberToCheck = i;
numberCheck(numberToCheck);
}
}
publicvoid numberCheck(int numberToCheck)
{
sumSoFar = 0;
for (int i = 1; i <= numberToCheck; i++)
{
//If the number is divisible by i, without remainder, add to sumSoFar
if (numberToCheck % i == 0)
sumSoFar += i;
}
sumOfDivisors = sumSoFar;
//Check to see if the sum of the divisors is equal to the number itself
checkPerfect(sumOfDivisors);
}
publicvoid checkPerfect(int x)
{
if (numberToCheck == x)
outputArea.append(numberToCheck +" is a perfect number.\n");
else
outputArea.append(numberToCheck +" is not a perfect number.\n");
}
}// end class
Thanks in advance,
Eoghain

