Search code examples
javafizzbuzz

Calling a method in another to populate an array


I would like to start by saying that it's been a couple years since I coded so my knowledge is a little shaky. I'm looking for some help, basically a push in the right direction. I am tasked with completing a program for a variation of the FizzBuzz game, The rules are: Enter 2 digits from 1-9, a Fizz number and a buzz number (ex: 2 7 )

  • if n is divisible by fizzNumber, or contains the digit fizzNumber, return "fizz"
  • if n is divisible by buzzNumber, or contains the digit buzzNumber, return "buzz"
  • however, if both the above conditions are true, you must return "fizzbuzz"
  • if none of the above conditions is true, return the number itself.

So i got that part down, my code is as follows, and it compiles correctly.

public String getValue(int n) {

boolean fz = false;     //fz will symbolize fizz in my logic
boolean bz = false;    //bz will symbolize buzz in my logic

//if n is divisible by fizzNumber, or contains the digit fizzNumber, return "fizz"
    if(n % fizzNumber == 0 || Integer.toString(n).contains(Integer.toString(fizzNumber)))
    fz = true;

//if n is divisible by buzzNumber, or contains the digit buzzNumber, return "buzz"
    if(n % buzzNumber == 0 || Integer.toString(n).contains(Integer.toString(buzzNumber))) //Check for buzz
    bz = true;

//if both the above conditions are true, you must return "fizzbuzz"
if (fz == true && bz == true)
    return("fizzbuzz");
 //return fizz
    else if (fz == true)
    return("fizz");
//return buzz
    else if(bz == true)
    return("buzz");
// return the number itself as a String
    else
    return Integer.toString(n); 
}

Now my next goal is to implement the getValues() method, to return an array of fizzbuzz values for a given range of integers. This method should internally call the getValue() method to compute the fizzbuzz value of a single integer, and store it to an array that is to be returned in the end.

public String[] getValues(int start, int end) {
        }

For example, if the fizz number is 3 and buzz number is 4, getValues(2,7) should return an array of Strings:

  {"2", "fizz", "buzz", "5", "fizz", 7}

I'm thinking of doing this with a for loop with something like this

for(start = 0; end >= start; start ++){

    }

but i really don't know how to implement the getValue method into my loop and store it in an array.

Can anyone help me out here?


Solution

  •     public String[] getValues(int start, int end) {
            List<String> valueList = new ArrayList<>();
            for (int i = start; i <= end; i++) {
                valueList.add(getValue(i));
            }
            String[] valueArr = new String[valueList.size()];
            valueArr = valueList.toArray(valueArr);
            return valueArr;
        }