📜  fizzbuzz java(1)

📅  最后修改于: 2023-12-03 15:15:05.510000             🧑  作者: Mango

FizzBuzz Java

FizzBuzz is a popular programming challenge used to test basic programming knowledge. The challenge requires a program to output a sequence of numbers while replacing certain numbers with "Fizz", "Buzz", or "FizzBuzz" depending on their divisibility. In this article, we will discuss how to implement the FizzBuzz challenge using Java.

The Challenge

FizzBuzz requires our program to output a sequential list of numbers starting from 1. However, if the number is divisible by 3, we replace it with the word "Fizz". If the number is divisible by 5, we replace it with "Buzz". If it's divisible by both 3 and 5, it's replaced with "FizzBuzz".

Implementation

To implement FizzBuzz in Java, we can use a for loop to loop through each number in the sequence. Inside the loop, we check if the current number is divisible by 3, 5, or both, and replace the number with the appropriate word. Here's the Java code:

for (int i = 1; i <= 100; i++) {
  if (i % 3 == 0 && i % 5 == 0) {
    System.out.println("FizzBuzz");
  } else if (i % 3 == 0) {
    System.out.println("Fizz");
  } else if (i % 5 == 0) {
    System.out.println("Buzz");
  } else {
    System.out.println(i);
  }
}

This code will output the FizzBuzz sequence for the first 100 numbers. We start the loop at 1 and continue until we reach 100. Inside the loop, we check if the current number is divisible by 3, 5, or both using the modulo operator (%). If a number is divisible by 3 and 5, we output "FizzBuzz". If it's only divisible by 3, we output "Fizz". If it's only divisible by 5, we output "Buzz". Otherwise, we just output the number itself.

Conclusion

FizzBuzz is a fun programming challenge that tests our basic programming knowledge. In Java, we can use a for loop and some conditional statements to implement the challenge and output the FizzBuzz sequence.