简体   繁体   中英

Replacing Integers with Strings Java

I'm doing a basic Java tutorial and below is the question.

Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."

My code is below

public static void fizzBuzz(){

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

        }
    }

It seemingly runs fine, but on closer inspection of the output, the "Fizz" and "Buzz" lines are printed AFTER the relevant numbers and are not printed as a replacement of the numbers

For example, I get the below

9
ÒBuzzÓ
10
ÒFizzÓ
11
12
ÒBuzzÓ
13
14
15
ÒFizzBuzzÓ
16

How do I get the relevant numbers to be replaced by the correct string statements instead of what I currently have? I only managed to find tips on converting strings to integers, but not replacement of integers to strings on SO, so I would appreciate any help :)

Move printing of number in else part of your if else ladder as like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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