FizBuzz program: how to make the output correct?

孤人 提交于 2019-12-31 04:32:11

问题


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 ");
            }

        }

    }
}

回答1:


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.




回答2:


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.




回答3:


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.



回答4:


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



来源:https://stackoverflow.com/questions/3220916/fizbuzz-program-how-to-make-the-output-correct

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