我想显示一条消息,指示我的value
数组中是否存在输入rollValue
。
我的代码无法正确识别此类数字。这个search
方法是我尝试过的,但为什么它没有显示正确的消息呢?
public void search(int value)
{
for (int i = 0; i < rollValue.length; i++)
{
if (rollValue[i] == value)
{
System.out.println(value + " was found");
}
else
{
System.out.println(value + " was not found");
}
break;
}
}
答案 0 :(得分:3)
您需要迭代(可能)每个值,然后才能决定是否找到它。制作两种方法。像
这样的东西private boolean hasValue(int value) {
for (int roll : rollValue) {
if (value == roll) {
return true;
}
}
return false;
}
然后,您可以通过调用search
hasValue
public void search(int value)
{
if (hasValue(value))
{
System.out.println(value + " was found");
}
else
{
System.out.println(value + " was not found");
}
}
或作为一行ternary喜欢
System.out.println(value + (hasValue(value) ? " was found" : " was not found"));
或您可以在return
中添加短路search
并执行类似
public void search(int value) {
for (int roll : rollValue) {
if (roll == value) {
System.out.printf("%d was found%n", value);
return;
}
}
System.out.printf("%d was not found%n", value);
}
答案 1 :(得分:2)
第一次迭代后,for
循环正在中断。将break
移到用于查找值的if
内,可能是这样的:
for (int i = 0; i < rollValue.length; i++)
{
if (rollValue[i] == value)
{
System.out.println(value + " was found");
break;
}
else
{
System.out.println(value + " was not found");
}
}
此外,您可能不需要打印&#34;未找到&#34;一直都是字符串,所以把它带走。