-6

Earlier in my code I call the method

public static boolean divides(int num, int denom)
{
    if (num%denom==0)
       return true;
    else return false; 
}

Later I am calling the method

public static boolean isLeapYear(int year)

I want to call divides in isLeapYear. Do I have to define divides all over again? Right now I have

public static boolean isLeapYear(int year)
{
public static boolean divides(int num, int denom)
{
   if (divides.class == true && (year%400 ==0) || ((year%4==0) 
       && (year%100 !=0)));
       return true;
       else return false;
}

}

And I get the error that divides is already defined, but when I don't put the whole public static etc. statement in there it wonders what divides is.

I'm also getting a host of other errors (such as it not being able to find year's type after I nest divides), but that's not the main one.

Alex
  • 295
  • 1
  • 3
  • 9

4 Answers4

5

You cannot nest method declarations. However, you can simply define them separately and call one from the other. That is the purpose of functions.

public static boolean divides(int num, int denom)
{
    if (num%denom==0)
       return true;
    else return false; 
}

public static boolean isLeapYear(int year)
{
    return divided(x, y);  // not sure what you are trying to divide, but fill in x and y.
}
Brandon
  • 9,822
  • 3
  • 27
  • 37
1

No, you cannot have nested methods in java. what you could do is make a call to divide() from your isLeapYear() method, passing the respective arguments to it.

public static boolean isLeapYear(int year)
{
divides(1, 2);
return result;
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

First you cannot declare nested methods.

Anyways you don't need to declare divides again.. If it's defined as static try to call it ContainingClass.divides(x,y);

And what's that divide.class thing?

Mike
  • 47,263
  • 29
  • 113
  • 177
Filipe Roxo
  • 622
  • 3
  • 10
1

i think you just want to call your method ...

public static boolean divides(int num, int denom)
{
    return (num % denom == 0); 
}

public static boolean isLeapYear(int year)
{
   return (divides(year, 4) && (!divides(year, 100) || divides(year, 400));
}

if the code in your if-else-statements simply return the result of your condition you can shorten your code a bit by returning the condition directly

Marco Forberg
  • 2,634
  • 5
  • 22
  • 33