FizBuzz program: how to make the output correct?

2019-03-02 03:53发布

I got a question about this program, it says: The FizzBuzz Challenge: Display numbers from 1 to x, replacing the word 'fizz' for multiples of 3, 'buzz' for multiples of 5 and 'fizzbuzz' for multiples of both 3 and 5. Th result must be:1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 ...

So my problem is at the time to print the output, I dont know what to do.

public class Multiplos {

    public static void main(String args[]) {

        for (int i = 1; i <= 100; i++) {

            if (i % 3 == 0) {
                System.out.print(i + " ");
                System.out.print(" fizz ");
            }

            if (i % 5 == 0) {
                System.out.print(" " + i);
                System.out.print(" " + "buzz ");
            }

            if((i % 3 == 0)&&(i % 5 == 0)){
                System.out.print(i + " ");
                System.out.print(" fizzbuzz ");
            }

        }

    }
}

标签: java fizzbuzz
4条回答
beautiful°
2楼-- · 2019-03-02 04:12

Hm, I think I'll only hint:

  1. Think of the correct order: What happens if a number is a multiple of 3, but also of (3 and 5)?
  2. There is an else if statement.
查看更多
Summer. ? 凉城
3楼-- · 2019-03-02 04:13

The problem is of course that when (i % 3 == 0)&&(i % 5 == 0) is true, the two preceding conditions are also true, so you get duplicated output. The easiest way to fix that is to check that the other condition is not true in the first two cases. I.e. make the first condition if((i % 3 == 0)&&(i % 5 != 0)) and the same for the second.

The other problem with your code is that you're printing the number when any of the cases is true, but you're supposed to print it when none of them are. You can fix that by making a fourth if-condition which checks that none of the conditions are true and if so, prints i.

Now if you did the above, you'll see that you ended up with some code duplication. If you think about it a bit, you'll see that you can easily fix that, by using if - else if - else if - else, which allows you to assume that the previous conditions were false when the current condition is checked.

查看更多
等我变得足够好
4楼-- · 2019-03-02 04:17

Here's the pseudocode:

for i in 1 to 100
   if(i % 5 == 0) AND (i % 3 == 0) print 'fizzbuzz'
   else if(i % 3 == 0) print 'fizz'
   else if(i % 5 == 0) print 'buzz'
   else print i

I'll leave it as an exercise for you to convert it into Java, as that might help with the understanding as to how this works.

查看更多
疯言疯语
5楼-- · 2019-03-02 04:27

Use else if so that the conditional don't overlap.

查看更多
登录 后发表回答