显示数组中包含的值

时间:2015-10-23 04:33:47

标签: java arrays printing

我想显示一条消息,指示我的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;
    }
}

2 个答案:

答案 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;一直都是字符串,所以把它带走。