Reputation: 21
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;
}
}
Upvotes: 2
Views: 65
Reputation: 201439
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);
}
Upvotes: 3
Reputation: 68715
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.
Upvotes: 2