【问题标题】:If-else statement in JavaJava中的if-else语句
【发布时间】:2014-10-29 15:04:46
【问题描述】:

我的程序有一点小问题,我确定它出在这个循环和 if-else 语句中:

for (int i = 0; i < xArray.length; i++)
        {
            if(searchNumber == xArray[i])
            {
                found = true;

                if(found)
                {
                    System.out.println("We have found your number " + searchNumber + " at position " + i + " in the array. " );
                }
                else
                {
                 System.out.println("No match was found.");                 
                }

                break;

            }

        }   

当我执行程序时发生的情况是,如果找到了 searchNumber(通过带有键盘输入的扫描仪获取),那么它将显示适当的消息,说明它已找到,但如果未找到,则没有消息显示。我尝试通过讲述每一行代码在做什么来调试它,但是当我进入这个循环时,我感到非常困惑。

【问题讨论】:

  • 你需要在循环外显示消息
  • 究竟是什么不工作,你对什么感到困惑?
  • 您试图在条件中显示“未找到”,只有在找到时才会触发。
  • 如果我在消息中没有 i 变量,这可以工作,但我想显示在数组的哪个索引中找到了数字。
  • searchNumber 是Strings 的数组吗?如果是这种情况,则需要使用.equals 方法; == 在这里不起作用。

标签: java if-statement for-loop break


【解决方案1】:

您将变量 found 设置为 true,然后进行测试 if (found),这也将始终为 true。 else 子句永远不会执行,因为found 永远不会为假。

根据您的描述,听起来您需要在循环外将 found 初始化为 false。然后,如果您得到匹配,请将其设置为 true。然后 if/else 语句可以移到 for 循环之外,并按照您的预期运行。

【讨论】:

    【解决方案2】:

    确保foundfalse 开头。然后在循环完成(或中断)后进行打印。

    boolean found = false;
    int i;//thanks @DaveNewton !
    for (i = 0; i < xArray.length; i++)
    {
        if(searchNumber == xArray[i])
        {
            found = true;
            break;
        }
    }   
    
    if(found)
        System.out.println("We have found your number " + searchNumber + " at position " + i + " in the array. " );
    else
        System.out.println("No match was found.");                 
    

    【讨论】:

    • @DaveNewton 我们不能给他完整的工作代码。相反,我们只是教育他,就像我们为 found 所做的那样:)
    • @sᴜʀᴇsʜᴀᴛᴛᴀ 那么我建议不要使用代码作为答案,而是使用合乎逻辑的解释。
    • 我已经尝试过这种方式,但是当我尝试初始化变量 i 时,循环开始给我一个错误。它现在可以工作了,为什么之前给我一个错误?
    • @MuseVyze 错误是什么? @DaveNewton 提到的问题是范围问题。 ifor 循环之外使用,因此它必须在for 循环之外进行初始化。否则代码不能引用它
    • 错误读取到变量 i 已经在 main 方法中初始化并突出显示了 for 循环,所以我猜这只是因为我初始化它的位置。
    【解决方案3】:

    对于初学者来说,您过早地进行了优化。除非您的阵列非常大,否则没有必要通过中断来停止检查。有效率是好事,但不能以不工作为代价。

    当你想提前结束一个循环时,我喜欢用这种方法用 while 循环而不是 for 循环:

    //init our sentinel flag and our counter
    boolean found = false;
    int i = 0 ;
    
    //while we have not found anything and we are less than the size of the array
    while (!found && i < xArray.length)
        {
            //check our condition
            found = (searchNumber == xArray[i]); 
            i++;          
        }   
    
    //finally react to the terminal state, found or not found and output as needed
    if(found)
      {
       System.out.println("We have found your number " + searchNumber + " at position " + i + " in the array. " );
      }
      else
       {
       System.out.println("No match was found.");                 
       }
    

    这在功能上等同于带有中断的 for 循环,如 @Cyber​​neticTwerkGuruOrcs 答案中所见。一些开发人员发现它更易于阅读。这也阻止了使用 break ,因为有时很难确定哪个语句被中断了。

    【讨论】:

    • 另外值得注意的是,您实际上并不需要found 标记值,您只需检查searchNumber == xArray[i]。这又是一个微优化,它并没有真正改善运行时,而是使代码更难阅读和理解。
    【解决方案4】:

    掸掉旧的 Java 帽子。这似乎更简洁?..

     int position = xArray.indexOf(searchNumber);
    
     if (position > -1) {
         System.out.println("We have found your number " + searchNumber + " at position " + position + " in the array. " );
     } else {
         System.out.println("No match was found.");       
     }
    

    只是想 - 如果这还不是一个 ArrayList,那么使用:

    java.util.Arrays.asList(xArray).indexOf(searchNumber)
    

    【讨论】:

      【解决方案5】:

      让我们分析一下你的代码的含义:首先,有一个循环扫描数组。这没有什么问题。在循环中有一个if-statement,条件为searchNumber == xArray[i],此条件检查是否存在匹配项。如果有,它将found 设置为true。然后 if 语句检查 found 并且由于在上一行中设置了 found true,语句中的代码将总是被执行,但 @987654327 中的代码@ 将永远被执行。所以这就是问题所在。

      所以查找数字的代码应该是这样的:

      for(int i : xArray){ //Foreach loop to simplify 
          if(i == searchNumber){//True if i == number we're searching for
              System.out.println("We have found your number " + searchNumber + " at position " + i + " in the array. " );//Print the message
              found = true; //The number has been found
              break; //cancel the loop as the number is found.
          }
      } 
      //The array has been searched completely
      if(!found){//if the number has not been found
          System.out.println("No match was found.");//Print the message
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 2015-08-18
        • 2012-05-11
        相关资源
        最近更新 更多