如果一个变量可以取n个值,我们应该检查这些值的有效性,或者假设如果所有n-i个检查都失败了,那将是第n个值。
例如,如果我们有一个将性别存储为M或F的变量。请使用以下命令:
If gender = "M"
do male_processing
else
do female_processing
endif
或这个:
If gender = "M"
do male_processing
else
if gender = "F"
do female_processing
else
print "Something has gone wrong Gender has a value " Gender
endif
endif
最佳答案
对于这种类型的构造,我喜欢使用switch语句。不是因为它更短(不是),而是更易读(恕我直言):
switch(gender) {
case "M":
doMaleSpecificStuff();
break;
case "F":
doFemaleSpecificStuff();
break;
default:
throw AnyError;
}
关于validation - 哪种编程方式更合适,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2955941/