Perfect number method

user1858350 picture user1858350 · Apr 9, 2013 · Viewed 7.4k times · Source

This program is supposed to take user input and determine whether or not it is a perfect number. When I try to compile it, I get the error Method testPerfect in class scalvert_Perfect cannot be applied to given types;

  • testPerfect(num);
  • required :int, int
  • found: int
  • reason: actual and formal argument list differ in length

My code:

import java.util.Scanner;

public class scalvert_Perfect
{
public static void main ( String args[] ) 
{
    Scanner input = new Scanner(System.in);
    int test;
    int num = 0;
    int counter = 0;

    do
    {
        System.out.print("How many numbers would you like to test? ");
        test = input.nextInt();

    }while(test < 1);

    do
    {
        System.out.print("Please enter a possible perfect number: ");
        num = input.nextInt();

        testPerfect(num);
        printFactors(num);

        counter++;

    }while(counter < test);
}


    public static boolean testPerfect(int num, int test)
    {
        int sum = 0;

        for(int i = 0; i < test ; i++)
            {
                if(num % i == 0)
                {
                sum += i;
                }       

            }
                if(sum == num)
                {
                return true;
                }
                else
                {
                return false;
                }
    }       

    public static void printFactors(int num)
    {
        int x;
        int sum = 0;

        for(int factor = num - 1 ; factor > 0; factor--)
            {
                x = num % factor;

                if (x == 0)
                {
                    sum = sum+factor;
                }
            }
                if(sum != num)
                {
                    System.out.printf("%d:NOT PERFECT",num);
                }

            if(sum == num)
                {       
                    System.out.printf("%d: ",num);

                        for(int factor=1; factor < num; factor++)
                            {       
                                x = num % factor;
                                if(x == 0)
                                {
                                    System.out.printf("%d ",factor);
                                }
                            }               
                }
                System.out.print("\n");
                sum = 0;
    }


}

Answer

Nanne picture Nanne · Apr 9, 2013

You function requires two integers because of this:

public static boolean testPerfect(int num, int test)

You call it with 1 integer here:

 testPerfect(num);

This is by the way exactly what the error says:

The function:

testPerfect(num);

Needs two integers

required :int, int

But you called it with one:

found: int

So the error is because the amount of arguments is not correct:

reason: actual and formal argument list differ in length