Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
題目:
寫一個程式輸出1到n的字串,但是遇到數字是3的倍數時輸出"Fizz",5的倍數時輸出"Buzz",同時是3和5的倍數時輸出"FizzBuzz。
解答:
public static void main(String[] args) {
System.out.print(fizzBuzz(15));
}
private static List<String> fizzBuzz(int n) {
List<String> stringList = new ArrayList<>(); //產生一個陣列物件stringList存放字串
for (int i = 1; i <= n ; i++) {
if (i % 3 == 0 && i % 5 == 0) { //判斷如果i除以3和5都餘0的話就新增"FizzBuzz"到字串陣列中
stringList.add("FizzBuzz");
} else if (i % 3 == 0) { //判斷如果i除以3餘0的話就新增"Fizz"到字串陣列中
stringList.add("Fizz");
} else if (i % 5 == 0) { //判斷如果i除以3餘0的話就新增"Buzz"到字串陣列中
stringList.add("Buzz");
} else { //都不是就把i轉成字串新增到字串陣列中
stringList.add(Integer.toString(i));
}
}
return stringList;
}