在int方法中返回'default'以传递给switch

时间:2013-04-14 14:26:49

标签: java

所以我正在为学校的作业做一个测试课,看起来像这样:

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方法使用默认值。如果所有内容都检出,我应该从compareObject(one, two)返回什么来触发切换方法中的默认大小写。

2 个答案:

答案 0 :(得分:1)

如果变量与任何情况都不匹配,则调用switch语句中的'default'。如果您有案例1和案例2,则任何非1或2的int都将转到默认块。

答案 1 :(得分:0)

您可以返回除1或2之外的任何int。您可以选择“默认”的内容。可能是0或-1或其他东西。

另见Thomas关于switch的回答。确保你理解`switch'语句的作用。