0

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);
    }
Community
  • 1
  • 1
nmu
  • 1,442
  • 2
  • 20
  • 40

2 Answers2

3

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.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
1

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))
lordoku
  • 908
  • 8
  • 22
  • if(word.toUpperCase().contains(String.valueOf(guess).toUpperCase)) - this seemed to actually work better for me thanks a lot – nmu Aug 04 '13 at 15:00