Finding a string in an array.
Let's say I have an Array of strings:
Code:
String[] a;
a = new String[3]
a[0] = "a"
a[1] = "b"
a[2] = "c"
and let's say I have another string:
How can I make it so I have it that when there is a "b" in the array then it will do something?
Like print "b is in the array"?
Re: Finding a string in an array.
Have you tried anything yet? If so, can you show us as well as any problems with the code? If not, what do you think might work? :)-:
Re: Finding a string in an array.
I have tried some stuff, but nothing worked.
Re: Finding a string in an array.
Quote:
Originally Posted by
rokit boy
I have tried some stuff, but nothing worked.
Let's see what you've tried, and then let's figure out why it didn't work.
Re: Finding a string in an array.
Well I tried random stuff like a["b"] but of course there is so many reasons why that is incorrect.
Then I searched through methods. Nothing.
Then I tried something clever from my side:
Code:
for (String thing : a) {
if (a.matches(thing)) {
print("Found it!");
}
}
but a wild NullPointerException has appeared from the wild grass and killed my pokemon.
Why the Exception?
Edit: I think I know what I did wrong.
Replace the String thing with stuff, hopefully it will work.
Re: Finding a string in an array.
Found it out!
Use it if you want.
Code:
for (String thing : a) {
if (thing == b) {
print("Found it!");
}
}
Re: Finding a string in an array.
Moved from Advanced Java
db
Re: Finding a string in an array.
Never use == to compare Strings or any other reference types. Use the .equals(...) method.
db
Re: Finding a string in an array.
Yep, i changed it in my original code.