所以我为学校的作业做了一个测试类,看起来是这样的:
public class Tester{
//variables.... some for the object to be tested, others for a Base object to be tested against
public void test(SpecialObject objectToBeTested){
SpecialObject baseObject = new SpecialObject();
int testCase = this.compareObjects(objectToBeTested, baseObject); //compare the two
switch (testCase){
case 1: System.out.println("CASE 1"); break;
case 2: System.out.println("CASE 2"); break;
default: System.out.println("Default, everything is good"); break;
//can't just make this case 0, because I think the switch requires a default
//so how do I pass an int to trigger the default?
}
}
public int compareObject(SpecialObject one, SpecialObject two) {
//compare one.this1 and two.that1
if ( one.this1 = two.that1 ) {return 1;};
//compare one.this2 and two.that2
if ( one.this2 = two.that2 ) {return 2;};
//......
// HERE IS WHERE I AM CONFUSED
// I want to do something like
return default;
//or
return "default";
// but can't because I need to pass an int
}
}由于我试图将所有比较保存在一个方法中(尽管稍后会将其抽象为多个方法),因此我尝试将一个整数传递回test(),同时将一个整数传递给switch方法。为了保持良好的信息,我想告诉自己哪个特定的比较失败了,我认为我需要将一些东西传递给switch方法才能使用default。如果一切正常,我应该从compareObject(one, two)返回什么来触发switch方法中的默认情况。
发布于 2013-04-14 22:28:44
如果变量与任何大小写都不匹配,则调用switch语句中的“default”。如果有case 1和case 2,则任何不是1或2的int都将转到默认块。
发布于 2013-04-14 22:33:48
你可以返回除1或2以外的任何默认值。你可以选择你想要的“int”。可能是0或者-1或者其他的东西。
另请参阅托马斯对switch的回答。确保您理解‘`switch’语句的作用。
https://stackoverflow.com/questions/16000124
复制相似问题