【问题标题】:Checking IF condition then bypass it to ELSE [closed]检查 IF 条件然后将其绕过到 ELSE [关闭]
【发布时间】:2021-02-04 03:36:51
【问题描述】:

我有一个 IF ELSE 条件语句块。假设这是我的代码

如何在不更改 A 或 B 的情况下获得代码的 IF ELSE of isTrue? 我试过 return true 但它不会返回,因为它在一个方法中。有什么关键字可以这样做吗?

public void test() {
 if (text1.equals("") {
   //Output error message
 } else if (text2.equals("") { 
   //Ouput error message
 .
 .
 .
 } else if (A!= null && (A > B))  {
   //GO TO ELSE condition without changing the A or B
 } else { if (isTrue){} }
}

【问题讨论】:

    标签: java android if-statement conditional-statements


    【解决方案1】:

    从其他条件句中取出最后一个条件句:

    public void test() {
       if (text1.equals("") {
          //Output error message
       } else if (text2.equals("") { 
          //Ouput error message
       } else if (A!= null && (A > B))  {
          //GO TO ELSE condition without changing the A or B
       }
    
       if (isTrue){ }
    }
    

    【讨论】:

    • 假设我想保持原样,有什么关键字可以使用吗?喜欢绕过它。
    • continue;
    • 继续;只能循环使用
    • 此解决方案将始终检查 isTrue(),这与 OP 发布的代码所做的相差甚远。
    【解决方案2】:

    看起来像您尝试使用该方法返回布尔值以检查任何参数... 如果那是真正的用途:

    public boolean testParams() {
    // check text 1
    if (text1.equals("this shouldnt be inside") {
        System.out.println("This is an error text 1 is not what expected");
        return false;
    }
    
    // check test2
    if (text2.equals("this shouldnt be inside") {
        // do sth
        .
        .
        .
        System.out.println("This is an error text 2 is not what expected");
        return false;
    }
        
    if(A < B && isTrue)
        return true;
    
    // in any other case return false
    return false;
    

    }

    如果它应该是一个 void(所以一个没有任何返回值的方法)这样做:

    public void testParams() {
    
    // check text 1
    if (text1.equals("this shouldnt be inside") {
        System.out.println("This is an error text 1 is not what expected");
        return;
    }
    
    // check test2
    if (text2.equals("") {
        // do sth and then at the end return with an error
        .
        .
        System.out.println("This is an error text 2 is not what expected");
        return;
    }
        
    if(A < B) {
        // do something when A is smaller then B
        if(isTrue) {
            // do sth when parameter isTrue is true...
        } else {
            // do another action when parameter isTrue = false...
        }
    } else {
        // do something when A is greater then B
    }    
    

    }

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多