Reputation: 21
Trying to find a solution to checking two different if conditions, and if neither are true output a third thing. Using a sample FizzBuzz code here to demonstrate the problem, when Fizz is for any multiple of 5 and Buzz for any multiple of 7. I wrote the "correct" way to do this first here.
//java
public class Fizzbuzz {
public static void main(String[] args) {
for(int i = 0; i < 100; i++ ) {
if(i % 5 == 0 && i % 7 == 0) {
System.out.println("FizzBuzz");
} else if(i % 5 == 0) {
System.out.println("Fizz");
} else if(i % 7 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}
I thought this was bad because using 4 if statements to check for two possible things is theoretically a waste. It could easily be simplified to something like this:
//java
public class Fizzbuzz2 {
public static void main(String[] args) {
for(int i = 0; i < 100; i++ ) {
if(i % 5 == 0) {
System.out.print("Fizz");
}
if(i % 7 == 0) {
System.out.print("Buzz");
}
if(i % 5 != 0 && i % 7 != 0) {
System.out.print(i);
}
System.out.print(\n);
}
}
}
Ideally, this could be simplified into something like this
if (x), print fizz
if (y), print buzz
if neither of the first two, print i
where printing fizz, buzz, and i don't add a newline, and print(/n)
is at the end.
Anyone have any idea how to do this (in any language?).
Upvotes: 0
Views: 75
Reputation: 1251
One way is to use the if
statements to set a value, and then use switch
/ case
to direct what happens based on the value.
For this example, I created a FizzBuzz type problem that test for multiples of 3, 5, and 7 for special handling. I tried to illustrate the flexibility of this approach by breaking the FizzBuzz pattern.
public static void fizzBuzzPop2 () {
for (int i = 1; i < 350; ++i) {
int flag = 0;
if (i % 3 == 0) { flag += 1; }
if (i % 5 == 0) { flag += 2; }
if (i % 7 == 0) { flag += 4; }
switch (flag) {
case 0: // nothing special
System.out.println (i);
break;
case 1: // multiple of 3
System.out.println ("Fizz");
break;
case 2: // multiple of 5
System.out.println ("Buzz");
break;
case 3: // multiple of 15 (3 and 5)
System.out.println ("FizzBuzz");
break;
case 4: // multiple of 7
System.out.println ("Pop");
break;
case 5: // multiple of 21 (3 and 7)
System.out.println ("PopQuiz!");
break;
case 6: // multiple of 35 (5 and 7)
System.out.println ("PopRocks");
break;
case 7: // multiple of 105 (3, 5, and 7)
System.out.println ("A busy day");
break;
default:
System.out.println ("****ERROR ERROR****");
break;
}
}
Each of 3 bits of flag
represents the result of one Boolean test. Treating the results as a single number allows use of switch
/ case
.
Upvotes: 2
Reputation: 349
If you are trying to make fewer comparisons, you can use it:
for( int i = 0; i < 100; i ++ ) {
String out = "";
if( i % 5 == 0 ) {
out = "Fizz";
}
if( i % 7 == 0 ) {
out += "Buzz";
}
if( out.isEmpty() ) {
out += i;
}
System.out.println( out );
}
Upvotes: 0