0

Java return

https://code.sololearn.com/cNcBMv4kD2Sm/?ref=app this code must create a blank string and do s = s+"Buzz" to fullfill the lastly return,because the lastly return return a number, got any other easier way instead of this?

2nd Jun 2019, 3:58 AM
Tzion
Tzion - avatar
4 Antworten
+ 3
public static String ans(int num){ if(num%3 == 0 && num%5 == 0){ return "FizzBuzz"; }else if(num%3 == 0){ return "Fizz"; }else if(num%5 == 0){ return "Buzz"; }else{ return Integer.toString(num); } } I’m kinda too tired to provide an explanation, but this would be an easier way write that. If you have any questions feel free to ask though
2nd Jun 2019, 4:51 AM
Jake
Jake - avatar
+ 9
//Here's an alternative approach: public static String ans(int num){ String s = num % 3 == 0 ? "Fizz" : ""; s = num % 5 == 0 ? s + "Buzz" : s; return s == "" ? Integer.toString(num) : s; }
2nd Jun 2019, 8:51 AM
David Carroll
David Carroll - avatar
+ 1
2nd Jun 2019, 8:52 AM
Tzion
Tzion - avatar
0
Jake knew it,thank you
2nd Jun 2019, 6:50 AM
Tzion
Tzion - avatar