【问题标题】:Is there another way of ignoring values using a while(true) loop besides using 'continue'?除了使用“继续”之外,还有另一种使用 while(true) 循环忽略值的方法吗?
【发布时间】:2015-03-26 04:45:42
【问题描述】:

我被要求获取用户输入并忽略不在 -30 和 40 范围内的值。为了跳过无效数字,我使用了“继续”语句。我在谷歌上搜索了消息来源说继续/中断是不好的做法。 IDE 还会发出“不必要的继续”警告。下面的代码是解决这个问题的好习惯,我应该覆盖警告还是解决它?

我的代码如下图:

public class Temperatures 
{

@SuppressWarnings("UnnecessaryContinue")
public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    // Write your code here. 
    while(true)
    {
        //ask user for input
        double userInput = Double.parseDouble(reader.nextLine());

        //makes sure temperature is within range, if it isn't ignores value and moves on
        if (userInput < -30.0 || userInput > 40.0)
        {
            continue;
        }
        //adds value to graph
        else
        {
            Graph.addNumber(userInput);
        }
     }
}

【问题讨论】:

  • 反转if 语句,使其仅在值处于可接受范围内时添加值...
  • 啊,你说得对,我真的很笨,谢谢!
  • 警告的原因是else。如果您删除了该警告也会消失。
  • continue 将跳过循环的其余部分到循环体的末尾,然后重复循环。但是没有什么可以跳过的。无论如何,该程序都不会执行else 分支,也没有什么可以跳过的。您可以删除该行(使if 部分为空{ }),程序将完全一样地工作。但是倒置if 语句会更好。

标签: java overriding continue suppress


【解决方案1】:

IDE 可能会显示警告,因为如果您删除 continue,您的代码将完全一样地工作。想一想。

【讨论】:

    【解决方案2】:

    IDE 还会抛出“不必要的继续”警告。

    这是一个不必要的continue。为什么?

    如果您的if 语句为真,else 将不会被执行。如果if 条件为假,则else 将被执行。因此,这里不需要continue

    continue 应该在以下情况下使用:

    while(true)
        {
            double userInput = Double.parseDouble(reader.nextLine());
            if (userInput < -30.0 || userInput > 40.0)
            {
                continue;
            }
            Graph.addNumber(userInput);
         }
    

    没有else 语句,因此现在您必须使用continue 来跳过当前迭代的进一步执行。

    【讨论】:

      【解决方案3】:

      您不需要在您的情况下使用 continue 。改用这个:

      if( userInput >= -30 && userInput <= 40){
          Graph.addNumber(userInput);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-24
        • 2012-10-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 2019-10-16
        • 1970-01-01
        • 1970-01-01
        • 2017-11-21
        相关资源
        最近更新 更多