有没有一种更有效的方式可以在不使用太多if-else语句的情况下进行类似的编码?
private int group1, group2, group3, group4;
private int total = 0
public void assignMembers()
{
group1 = (int)((6 * Math.random()) + 1);
group2 = (int)((6 * Math.random()) + 1);
group3 = (int)((6 * Math.random()) + 1);
group4 = (int)((6 * Math.random()) + 1);
}
public void calculateSomething()
{
if(group1 == 3)
{
total += 2;
}
else if(group1 == 5)
{
total += 4;
}
if(group2 == 3)
{
total += 2;
}
else if(group2 == 5)
{
total += 4;
}
if(group3 == 3)
{
total += 2;
}
else if(group3 == 5)
{
total += 4;
}
if(group4 == 3)
{
total += 2;
}
else if(group4 == 5)
{
total += 4;
}
{
如果组中有3个成员,则if-else语句将总数加2;如果组中有5个成员,则if-else语句将总数加4。
我知道我可以使用“组”数组做一些更有效的事情,但是有没有数组的方法吗?也许是无需让if-else如此重复就可以使calculateSomething方法获取每个组的团队成员数量的方法吗?任何建议,将不胜感激。
如果您似乎在代码中发现了冗余模式,那么您就该创建一个可重用的函数了。
private int group1, group2, group3, group4;
private int total = 0;
public void assignMembers()
{
group1 = (int)(Math.random()*6 + 1);
group2 = (int)(Math.random()*6 + 1);
group3 = (int)(Math.random()*6 + 1);
group4 = (int)(Math.random()*6 + 1);
calc(group1);
calc(group2);
calc(group3);
calc(group4);
}
public void calc(int group)
{
switch (group){
case 3:
total += 2;
break;
case 5:
total += 4;
break;
}
}
更新答案-因为要求是:该方法必须在类外部调用。
private int group1, group2, group3, group4;
private int total = 0;
public void assignMembers()
{
group1 = (int)(Math.random()*6 + 1);
group2 = (int)(Math.random()*6 + 1);
group3 = (int)(Math.random()*6 + 1);
group4 = (int)(Math.random()*6 + 1);
}
private void calc(int group)
{
switch (group){
case 3:
total += 2;
break;
case 5:
total += 4;
break;
}
}
public void calculateSomething(){
calc(group1);
calc(group2);
calc(group3);
calc(group4);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句