Reputation: 1519
I am trying to use the indexOf method to find if a char is in a word but since the char cannot be dereferenced i assumed it should be converted to a String i tried using these Methods but it does not seem to be comparing accurately - how should i be using a referenced char in 'indexOF'. here is my code, if this is a stupid problem with my code logic then i apologise
guess = JOptionPane.showInputDialog("Enter letter ").toUpperCase().charAt(0);
if((String.valueOf(guess)).indexOf(word.toUpperCase())>=0)
{
for(int k = 0; k<word.length(); k++)
{
if(guess==charwo[k])
{
charda[k]=charwo[k];
}
}
}
else
{
guesses = guesses-1;
System.out.println("guesses left "+guesses);
}
Upvotes: 0
Views: 1391
Reputation: 55609
I think you're using indexOf
the wrong way around. Assuming your looking for the index of guess
in word
(the other way around doesn't really make sense), it should be:
word.toUpperCase().indexOf(guess)
No dereferencing problems here since there an indexOf(int)
function.
contains
would probably make for slightly more readable code, unfortunately it takes a CharSequence
parameter (superclass of String
), so you'd need to convert guess
to String
in this case. The way I usually convert primitives to String
like this:
word.toUpperCase().contains(""+guess)
Though I'm not saying it's better than String.valueOf
, I just use it because it's less typing.
Upvotes: 3
Reputation: 1112
If I'm not mistaken, I think this line is backwards:
if((String.valueOf(guess)).indexOf(word.toUpperCase())>=0)
should be
if(word.toUpperCase().indexOf(String.valueOf(guess).toUpperCase) >=0)
you could also do
if(word.toUpperCase().contains(String.valueOf(guess).toUpperCase))
Upvotes: 1