5 Replies Latest reply: Mar 25, 2008 1:37 PM by 807591

# Use a void method as int?

See i have a program to compute hcf and lcm.
Im using a void method to calculate hcf, so it prints it to the user.Now in the LCM, I use this method to get the hcf of the numbers, and then divide their product by it to get lcm.
I declared the hcf an instance variable , but i need to make sure the hcf is computed before lcm is asked, so i call hcf from lcm
The problem is the user will see both hcf and lcm when asking for lcm. How do i fix this?
Code:
``````public class HCFNLCM
{
int max;
public void hcf(int a, int b)
{
max=1;
for (int i=2;i<=Math.min(a,b);i++)
{
if (a%i==0 && b%i==0)
{
if (i>max)
max=i;
}
}
System.out.println("HCF: "+max);
}

public void lcm(int a, int b)
{
hcf(a,b);
System.out.println("LCM: "+((a*b)/max));
}
}

``````
• ###### 1. Re: Use a void method as int?
You need to separate the display aspects of your program from the logical aspects. i.e., have your hcf method not display anything, but rather return an int. Let the calling method decide if it will display the results, use the results, or both.
• ###### 2. Re: Use a void method as int?
Couple solutions:

1) Add another parameter to hcf(). Make a boolean parameter, that if true, will print the hcf, and if false, it won't.
2) (preferred) Don't do your printing from hcf() and lcm(). Do your printing from the calling class, and make hcf() and lcm() return ints.
• ###### 3. Re: Use a void method as int?
dont print out HCF in the HCF method.

dont print the LCM in the LCM method.

print them when you actually need to print the values.
• ###### 4. Re: Use a void method as int?
have your hcf method not display anything, but rather return an int. Let the calling method decide if it will display the results, use the results, or both.
Don't do your printing from hcf() and lcm()
print them when you actually need to print the values.
UT announcer: MULTIKILL, KILL, kill, kill...
• ###### 5. Re: Use a void method as int?
newark wrote:
UT announcer: MULTIKILL, KILL, kill, kill...
LOL