perfect numbers

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Sep 2005
Posts
8

## perfect numbers

this is a class to determine the perfect numbers between 1 and 100..
public class Perfect {

public static void main(String[] args) {
// Perfect numbers

for ( int i=2; i<=1000; i++ )
{
int sum = 0;
for ( int j=1 ; j<i ; j++ )
{
if ( i % j == 0 )
{
sum = sum + j;
}
}
if ( sum == i )
{
System.out.println("" + i + " is a perfect number" );
System.out.print("Factors are: " );
for ( int f=1; f<i ; f++ )
{
if ( i % f == 0 )
{
System.out.print(" " + f );
}
}
System.out.println();
}
}
}
}

how can i do it as an applet using JTextArea??

2. Senior Member
Join Date
Mar 2004
Posts
635
extend JApplet from your Perfect class.

3. ## Like this

Code:
```import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Perfect
extends JApplet
implements ActionListener {
JScrollPane jScrollPane1 = new JScrollPane();
JPanel ctrlPanel = new JPanel();
JButton ppnBtn = new JButton();
JTextArea reportTA = new JTextArea();
JButton clearBtn = new JButton();

public Perfect() {}

public void init() {
try {
jbInit();
// hook up buttons
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Print perfect numbers to textarea
*/
private void printPerfectNumbers() {
for (int i = 2; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum = sum + j;
}
}
if (sum == i) {
reportTA.append("" + i + " is a perfect number\n");
reportTA.append("Factors are: ");
for (int f = 1; f < i; f++) {
if (i % f == 0) {
reportTA.append(" " + f);
}
}
reportTA.append("\n");
}
}
}
/**
* Set up GUI
*/
private void jbInit() throws Exception {
ppnBtn.setText("Print Perfect Numbers");
reportTA.setText("");
clearBtn.setText("Clear");
}
/**
* Handle button clicks
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ppnBtn) {
printPerfectNumbers();
}
else if (e.getSource() == clearBtn) {
reportTA.setText("");
}
}
/**
* MAIN for testing applet (uses the applet as a JPanel)
*/
public static void main(String[] args) {
JFrame f=new JFrame("Applet Test");
f.getContentPane().setLayout(new GridLayout());
Perfect applet=new Perfect();
applet.init();
f.setBounds(20,20,300,200);
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise