簡體   English   中英

Java中的if-else語句

[英]If-else statement in Java

我的程序有一個小問題,我確定它位於此循環和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(通過帶有鍵盤輸入的Scanner來獲取),那么它將顯示適當的消息,說明已找到該消息,但是如果未找到,則不會顯示任何消息。 我試着通過每一行代碼在做什么來調試它,但是當我進入這個循環時,我感到非常困惑。

確保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.");                 

去掉舊的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)

您將found變量設置為true,然后測試if (found) ,它也將永遠為true。 else子句將永遠不會執行,因為found永遠不會為假。

根據您的描述,聽起來您需要在循環外將found初始化為false。 然后,如果您找到匹配項,請將其設置為true。 然后,可以將if / else語句移到for循環之外,並按預期運行。

對於初學者,您過早地進行了優化。 除非您的陣列過大,否則不必中斷檢查。 提高效率是件好事,但不能以不工作為代價。

當您想盡早結束循環時,我喜歡將這種方法與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,有時可能很難確定中斷了哪個語句。

讓我們分析一下代碼的含義:首先,有一個遍歷數組的循環。 沒錯。 在循環中,有一個條件if-statement ,條件為searchNumber == xArray[i]該條件檢查是否存在匹配項。 如果有一個,它設置found為true。 然后if語句進行檢查found ,並為found已設置true的前行,在聲明的代碼就一定會執行,但在代碼else永遠不會被執行。 這就是問題所在。

因此查找數字的代碼應如下所示:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM