Perfect number in java using methods for homework

Cesco picture Cesco · Dec 3, 2014 · Viewed 7.3k times · Source

I had a to write a homework for class and got stuck with it, can't figure out how to make it set up correctly like it is supposed to. I appreciate any help I get thank you. This is the assignment:

An integer number is said to be a perfect number if its factors, including 1 (but not the numbers itself), sum to the number. For example,6 is a perfect number, because 6=1+2+3. Write method Perfect that determines whether number is a perfect number. Use this method in an application that determines and displays all the perfect numbers between 2 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect.

Output:

6 is perfect.
Factors:1 2 3
28 is perfect.
Factors: 1 2 4 7 14
496 is perfect.
Factors: 1 2 4 8 16 31 62 124 248

and here is the code I got stuck with:

public class Homework4 {

    public static void main(String[] args) {

        for(int num=2;num<=1000;num++)
        {
            if(perfect(num))
            {
                System.out.println(num + " is perfect.");
                System.out.printf("Factors: ",perfect(num));

            }

        }
    }
        public static Boolean perfect(int num)
        {
            int sum = 0;

            for(int i=1;i<num;i++)
            {
                if (num % i == 0)
                {
                    sum+=i;
                }
            }
            if(num==sum)
            {
            for(int i=1;i<num;i++)
            {
                if (num % i == 0)
                {
                    System.out.print(i+" ");
                }
            }


            }
            return sum==num;
        }

}

run:

1 2 3 6 is perfect.
1 2 3 Factors: 1 2 4 7 14 28 is perfect.
1 2 4 7 14 Factors: 1 2 4 8 16 31 62 124 248 496 is perfect.
1 2 4 8 16 31 62 124 248 Factors: BUILD SUCCESSFUL (total time: 0 seconds)

Answer

Dawood ibn Kareem picture Dawood ibn Kareem · Dec 3, 2014

There are two ways you could fix this.

  • You could break your perfect method into two separate methods - one that checks whether the number is perfect, and one that prints its factors. Call the first one when you're checking - and if it returns true, then call the second one.

Or

  • You could move the line that prints ... is perfect into the method itself. Then remove the entire if block from main.