简体   繁体   中英

Displaying values contained in an array

I would like to display a message indicating if an input value is present in my rollValue array.

My code does't correctly identify such numbers. This search method is what I have attempted, but why doesn't it display the correct message?

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;
    }
}

You need to iterate (potentially) every value, before you can decide if it was found. Make two methods. Something like

private boolean hasValue(int value) {
    for (int roll : rollValue) {
        if (value == roll) {
            return true;
        }
    }
    return false;
}

Then you can implement search by calling hasValue like

public void search(int value)
{
    if (hasValue(value)) 
    {        
        System.out.println(value + " was found");
    }
    else
    {
        System.out.println(value + " was not found");
    }
}

or as a one line ternary like

System.out.println(value + (hasValue(value) ? " was found" : " was not found"));

or you could add a short-circuit return in search and do something like

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);
}

Your for loop is breaking after the first iteration. Move break inside the if used to find the value, maybe like this:

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");
            }
        }

Also you may not need to print the "was not found" string all the time so take it away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM