简体   繁体   English

为什么这段代码不起作用? FizzBu​​zz JAVA

[英]Why doesn't this code work? FizzBuzz JAVA

I cant get "FizzBuzz". 我无法获得“ FizzBu​​zz”。 No matter what the input, the "FizzBuzz" code isn't running. 无论输入什么,“ FizzBu​​zz”代码都不会运行。 What did I do wrong? 我做错了什么?

public String[] fizzBuzz(int start, int end) {

int diff = end-start;
String[] array = new String[diff];

for (int i = 0; i < diff; i++) {
    if (start%3 == 0 && start%5 == 0) array[i] = "FizzBuzz";
    if (start%3 == 0 || start%5 == 0) {
        if (start%3 == 0) array[i] = "Fizz";
        if (start%5 == 0) array[i] = "Buzz";
    }
    else {
        array[i] = String.valueOf(start);
    }
    start++;
    }

    return array;
}

Logic in your if statements is a bit busted, using your code as the starting point, you'd have to do something like this. 如果您的if语句中的逻辑有些破烂,以您的代码为起点,则必须执行以下操作。

if (start%3 == 0 && start%5 == 0) {
    array[i] = "FizzBuzz";
}
else if (start%3 == 0 || start%5 == 0) {
    if (start%3 == 0) array[i] = "Fizz";
    if (start%5 == 0) array[i] = "Buzz";
}
else {
    array[i] = String.valueOf(start);
}
String s = "" + i;
if ((i % 3) == 0) {
    s += " Fizz";
}
if ((i % 5) == 0) {
    s+= " Buzz";
}
System.out.println(s);

This code snippet placed in a loop will print Fizz, Buzz and Fizz Buzz on i divisible by 3, 5 and 15 respectively. 放在循环中的此代码段将在i上分别打印Fizz,Buzz和Fizz Buzz,分别被3、5和15整除。

you should try this. 你应该试试这个。

    class FizzBuzz{
    public static void main(String args[]){
        int n = 100;
        for(int i=0;i<=n;i++){

            if((i % 3) == 0 && (i % 5) != 0){
                 System.out.println("Fizz");
            }
            else if((i % 5) == 0 && (i % 3) != 0){
                System.out.println("Buzz");
            }else if((i % 3) == 0 && (i % 5) == 0){
                System.out.println("FizzBuzz");
            }else{
                System.out.println(""+i);
            }

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM