Verses of Truth Verses of Truth - 25 days ago 11
Java Question

How to connect variables between private methods and public methods

I am a beginner trying to learn Java so I started off by doing the famous FizzBuzz project. This project requires the user to make an instance of a FizzBuzz class and pass in a value. Now the code, which is in another Java Class, reads the number the user passes in and makes a list of all the numbers between 1 and the number the user passed in. I was able to complete this until I got to the next exercise which required me to create 3 private boolean methods (see below):





public class FizzBuzzRunner
{
private boolean fizz(int num)
{
return num % 3 == 0;
}
private boolean buzz(int num)
{
return num % 5 ==0;
}
private boolean fizzbuzz(int num)
{
return num % 3 ==0 && num % 5 == 0;
}

public void fizzBuzz(int num)
{
for (int i = 1; i < num + 1; i++)
{
if (fizzbuzz(num))
{
System.out.println("FizzBuzz");
} else if (fizz(num))
{
System.out.println("Fizz");
} else if (buzz(num))
{
System.out.println("Buzz");
} else {
System.out.println(i);
}
}

} </code>


Now my code is obviously wrong. Firstly, how can I link the variable in the public method (int num) so that it's the same variable in the private methods? My second question is if the arguments inside the If statements are fine. Essentially what I want is, for example, if fizz method is true print "fizz" etc.

Answer

Pass the value if i not num

public void fizzBuzz(int num)
{
    for (int i = 1; i < num + 1; i++)
    {
        if (fizzbuzz(i))
        {
            System.out.println("FizzBuzz");
        } 
        else if (fizz(i))
        {
            System.out.println("Fizz");
        } 
        else if (buzz(i))
        {
            System.out.println("Buzz");
        } 
        else {
            System.out.println(i);
        }
    }

}
Comments