【问题标题】:Continue Statement in a Java FunctionJava 函数中的 Continue 语句
【发布时间】:2012-09-10 23:05:09
【问题描述】:

我想创建这样的逻辑:如果 s2 为 null,则调试器会跳过所有复杂的字符串操作并返回 null 而不是 s1 + s2 + s3,如第一个 if 块中所示。我在某个地方错了吗?

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     continue;
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

【问题讨论】:

  • 您需要一个循环才能使用continue
  • @bouncingHippo:您是否有兴趣仅跳过空字符串,或者如果 s2 是空字符串(“” - 这不是空字符串),您是否还想返回 null
  • 是的,我想在 s2==null 时返回 null,而 s2=""

标签: java algorithm iteration continue


【解决方案1】:

不要在那里使用 continue , continue 是 for 循环,比如

for(Foo foo : foolist){
    if (foo==null){
        continue;// with this the "for loop" will skip, and get the next element in the
                 // list, in other words, it will execute the next loop,
                 //ignoring the rest of the current loop
    }
    foo.dosomething();
    foo.dosomethingElse();
}

只是做:

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

【讨论】:

  • 所以对于你的解决方案,如果s2==null,它会返回null而不返回(s1+s2+s3)?
  • 你可能已经测试过了,但是是的,它就是这么做的 =)
【解决方案2】:

continue 语句用于循环(forwhiledo-while),而不用于if 语句。

你的代码应该是

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

【讨论】:

    【解决方案3】:

    那里不需要continuereturn null; 就足够了。

    continue 在您希望循环跳过块的其余部分并继续下一步时在循环中使用。

    例子:

    for(int i = 0; i < 5; i++) {
        if (i == 2) {
            continue;
        }
    
        System.out.print(i + ",");
    }
    

    将打印:

    0,1,3,4,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      相关资源
      最近更新 更多