gpt4 book ai didi

java - Java 中的 if-else 语句

转载 作者:行者123 更新时间:2023-12-01 22:43:47 25 4
gpt4 key购买 nike

我的程序有一个小问题,我确定它出在这个循环和 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(通过扫描仪使用键盘输入获取),那么它将显示相应的消息,表示已找到它,但如果未找到,则不会显示任何消息显示。我尝试通过告诉自己每行代码正在做什么来调试它,但是当我进入这个循环时,我感到非常困惑。

最佳答案

确保 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 - Java 中的 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25672682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com