Hi everyone,

I have a simple applet to display the perfect numbers from 1-500...but when the numbers that are considered to be perfect are displayed, they are written over the top of each other...

Ive used a simple for loop, but it doesnt seem to help...does anyone have any ideas as to what is going on?

Thanks very much!

import java.applet.*;
import java.awt.*;
 
public class PerfectNumbers extends Applet {
 
    int maxNum=500;
    int perfectCount=0;
 
    public void paint (Graphics g){
    {        
        for(int ctr=maxNum;ctr>=2;ctr--)
        {
            int sum = 0;
            int sum2 = 0;
            for(int ctr2 = ctr; ctr2>=2; ctr2--)
            {
                if(ctr%ctr2==0)
                {
                    sum = sum+(ctr/ctr2);
                    sum2 = ctr/ctr2;
                }
            }
        if(ctr==sum)
        {
            for (int i = 1; i<=4; i++)
            {
                g.drawString(""+ctr,20,120+i*20);
                i++;
            }
            perfectCount++;
            }            
        }
    }
    g.drawString("There are "+perfectCount+" Perfect numbers from 1-" +maxNum,20,60);    
}
}
Member Avatar for iamthwee

When things don't work as you expect try to simplify the code to find out what's going wrong.

It seems like you're moving the y coordinate instead of the x one.

import java.applet.*;
import java.awt.*;
 
public class PerfectNumbers extends Applet 
{
 
    int maxNum=500;
    int perfectCount=0;
 
    public void paint (Graphics g)
    {
      {        
          int j = 0;
          for (int i=0; i <100; i++)
          {
                g.drawString(i+" ",20+(j),80);
                j = j + 20;
          }
                //i++;
            
      }
    g.drawString("There are "+perfectCount+" Perfect numbers from 1-" +maxNum,20,60);    
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.