【问题标题】:Complex Conditionals and Unreachable Statements复杂的条件和不可达的语句
【发布时间】:2019-02-06 12:42:31
【问题描述】:

我对 Java 很陌生,遇到了一些麻烦。我觉得这很容易解决。基本上,如果满足两个条件,我希望返回一个声明。下面是我附加的代码。

boolean Windy = false;

if (Windy = true) 
  return "It is Windy";
else 
  return "Not Windy";

if (temperature < 30);
{return "Too Windy or Cold! Enjoy watching the weather through the window";

在我尝试更改脚本后引发了其他错误,声称需要返回语句。

【问题讨论】:

  • 不要附加代码,复制粘贴到问题中,在代码块中。

标签: java unreachable-statement


【解决方案1】:

您的代码包含几个错误:

  1. Windy = true 中的= 应改为=== 是赋值,== 是检查相等性。
  2. 因为您的第一个 if (Windy = true) return "It is Windy"; else return "Not Windy"; 将始终返回两者之一,所以它下面的其余代码无法访问并且永远不会被执行。
  3. 即使可以访问,也应删除 if (temperature &lt; 30); 处的尾随分号。
  4. 方法中的{}-block 不是必需的。

我认为这就是您正在寻找的代码:

boolean windy = false;

if(windy){
  return "It is Windy";
} else if(temperature < 30){
  return "Too Windy or Cold! Enjoy watching the weather through the window";
} else{
  return "Not Windy";
}

当然,将windy 设置为false 硬编码有点使得第一次检查也无法进行。但我认为这只是您的示例代码,在您的实际代码中您检索 windy 作为类变量或方法参数。

此外,由于windy 本身是一个布尔值,所以== true 是多余的,只需if(windy) 就足够了。

PS:Java 中的变量名最好是驼峰式,所以在这种情况下使用windy 而不是Windy
我还在 if/else-if/else 语句周围添加了括号。它们不是必需的,如果您真的愿意,可以不使用它们,但修改代码更容易,以后不会出错。

【讨论】:

  • 最后一条评论:风格方面,很多人建议永远不要没有大括号。因此,即使您的 for/if/... 只有 one 语句,您也要在其周围加上大括号。添加第二条语句的情况发生得太频繁了,人们忘记了它在 if/for/...范围的外部
  • @GhostCat 也已修改。我必须承认我个人更喜欢不带括号,但我绝对同意你的观点(尤其是对于新的 Java 开发人员),所以我将它们添加到代码 sn-p 和底部的 PS 中。
【解决方案2】:

好的,我检查了您的图片(我通常不这样做)并在您的代码中发现了几个问题。

public static String getWeatherAdvice(int temperature, String description)
{
  { // REMOVE THIS BRACKET
    if ( Windy = true) // = signifies an assigning a value, not a comparison. Use ==
      return "It is Windy";
    else
      return "Not Windy";

    if ( temperature < 30 ); // Since the above if-else will always return a value, this
    // code can not be reached. Put this if before the previous if-else. Also: remove the ; after the if statement, otherwise, it ends the if, and the return statement might be triggered.
    { // don't put this bracket if you have a ; after the if
      return "Too windy ... ";
    } // don't put this bracket if you have a ; after the if
  } // REMOVE THIS BRACKET
}

您的代码的更正版本(可能是):

public static String getWeatherAdvice(int temperature, String description)
{
   if ( temperature < 30 )
    { 
      return "Too windy ... ";
    } 

    if ( Windy == true) // can also be written as: if ( Windy ) 
      return "It is Windy";
    else
      return "Not Windy";    
}

【讨论】:

    【解决方案3】:

    您可以使用“&&”= 和“||”来比较标准= 或:

    if (Windy && temperature < 30) {
    return "it's windy and temperature is <30";
    } else if (!Windy && temperature > 30) {
    return "Not Windy";
    }
    

    【讨论】:

    • 不要使用== true== false。很容易错过=s 之一并将其更改为作业。 Windy == true 更容易写成Windy
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多