FizBuzz program: how to make the output correct?

∥☆過路亽.° 提交于 2019-12-02 05:35:37

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.

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.

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!