问题
I'm writing this problem for school and I have some issues with it. I can't get "printFizzBuzz" to actually go up and calculate the wrapper function "FizzBuzz". I am required to use loops and was attempting to use a FOR loop. Beginner programmer here so no, I haven't used loops much at all. Any tips or pointers? ;)
The instructions are as follows.
public static String FizzBuzz(int number)
{
if( (number%3==0) && (number%5==0)) {
return "FizzBuzz";
}
else if( number%3 == 0 ) {
return "Fizz";
} else if( number%5 == 0 ) {
return "Buzz";
} else {
return ""+number;
}
}
/*
* use a for loop to print the appropriate FizzBuzz values (feel free to
* call the provided FizzBuzz function) for values from from to to,
* including both of those values. Each value should be printed in a separate line.
*/
public static void printFizzBuzz(int from, int to, PrintStream out)
{
for (int i = 1; i <= to; ++i){
FizzBuzz(++i);
}
}
回答1:
Take a look at the FizzBuzz function:
public static String FizzBuzz(int number)
public static STRING tells you that this function returns a string.
Each time you write
FizzBuzz(++i);
imagine this to be a string like "Fizz"
So in your program what you really wrote is
for (int i = 1; i <= to; ++i){
"Fizz";
}
That doesn't look good right? You actually need to assign this string to something, or do some stuff with it. For example:
for (int i = 1; i <= to; ++i){
String a = "Fizz";
System.out.println(a);
}
Better, this is printing it to the standard output! However your function has already one PrintStream out parameter that you can use to print!
for (int i = 1; i <= to; ++i){
String a = FizzBuzz(i++);
out.println(a);
}
Now let's take a look at the for loop: it creates a variable i that starts from 1 (int i = 1), checks the condition ( i <= to) and if the condition is satisfied it executes the body of the loop. After that it increments i by 1 (++i).
So the first 3 rounds of the loop will be unrolled like this:
int i = 1;
if(i<=to){
String a = FizzBuzz(i++);
out.println(a);
}
++i; //i = 3;
if(i<=to){
String a = FizzBuzz(i++);
out.println(a);
}
++i; //i = 5;
if(i<=to){
String a = FizzBuzz(i++);
out.println(a);
}
++i; //i = 7;
Looks like we still have a problem here. Why is i 3, then 5 and then 7? What happened to 2,4,6? The problem is that you are also incrementing i by 1 when calling FizzBuzz (FizzBuzz(i++)).
This is wrong, the loop is already incrementing i for you by 1, if you increment i by 1 more, it will be incremented by 2 each round.
I'll leave the final fix to you.
来源:https://stackoverflow.com/questions/39652324/how-to-create-the-fizzbuzz-using-loops-in-java