如何减少if语句 [英] How to reduce if statements
问题描述
下面的程序可以根据需要运行,但是如何减少if语句的数量。有人告诉我,如果你的函数包含2个或更多if语句,那么你做错了。有什么建议么?我已经尝试过使用switch语句但是没有用,因为大小写不能是布尔值。
The program below functions as necessary but how do I reduce the amount of if statements. I have been told that if your function contains 2 or more if statements then your doing it wrong. Any suggestions? I've tried using switch statements but that hasn't worked because the case can't be a boolean.
for(int i = 1; i < 100; i++)
{
if(i % 10 == 3)
{
System.out.println("Fizz" + "(" + i + ") 3%10");
}
if(i / 10 == 3)
{
System.out.println("Fizz" + "(" + i + ") 3/10");
}
if(i % 10 == 5)
{
System.out.println("Buzz" + "(" + i + ") 5%10");
}
if(i / 10 == 5)
{
System.out.println("Fizz" + "(" + i + ") 5/10");
}
if(i / 10 == 7)
{
System.out.println("Fizz" + "(" + i + ") 7/10");
}
if(i%10 == 7)
{
System.out.println("Woof" + "(" + i + ") 7%10");
}
if(i % 3 == 0)
{
System.out.println("Fizz" + "(" + i + ") 3%==0");
}
if(i % 5 == 0)
{
System.out.println("Buzz" + "(" + i + ")5%==0");
}
if(i % 7 == 0)
{
System.out.println("Woof" + "(" + i + ")7%==0");
}
if( (i % 7 !=0 ) && (i % 3 !=0 ) && (i % 5 !=0 )
&& (i % 10 !=3) && (i % 10 !=5 ) && (i%10 !=7 ) )
System.out.println(i);
}
推荐答案
如何创建方法案例:
public void printIfMod(int value, int mod){
if (value % 10 == mod)
System.out.println(...);
}
public void printIfDiv(int value, int div){
if (value / 10 == div)
System.out.println(...);
}
然后而不是一堆如果
你有一组调用这两种方法。您甚至可以创建一个调用上述两种方法的方法。
Then instead of a bunch of if
you have a set of calls the the two methods. You might even create a single method that calls both of the above.
public void printIf(int value, int div){
printIfMod(value, div);
printIfDiv(value, div);
}
for(int i = 1; i < 100; i++) {
printIf(i, 3);
printIf(i, 5);
....
}
在上面的代码中 ifs
对我来说比重复代码的数量少。
In the above code the number of ifs
is less of an issue to me than the amount of repeated code.
这篇关于如何减少if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!