tamzoro
tamzoro

Reputation: 45

Compare letter via a word

I don't understand my error: I have to compare a letter via a word for example home.

If the user enters the letter o a message must appear to inform that the letter o exists.

Else another message must appear to inform that the letter is not good.

My problem is that when I enter the letter o, I don't have the message that I have to get. Normally, the letter exists...

for(int i=0;i<9;i++){
      System.out.print("Enter your letter : ");
      char user_input_letter = enter.next().charAt(0);
      if(word_to_search.charAt(0) == user_input_letter){
        System.out.println("The letter exists !!");
      }
      else{
        System.out.println("This letter does not exist ! ");
      }
    }

Upvotes: 0

Views: 63

Answers (2)

Andrei Tigau
Andrei Tigau

Reputation: 2058

This should work:

for(int i=0;i<9;i++){
     System.out.print("Enter your letter : ");
     char user_input_letter = enter.next().charAt(0);

     if(word_to_search.contains(user_input_letter+"")){
           System.out.println("The letter exists !!");
         }
     else{
    System.out.println("This letter does not exist ! ");
             }

    }

Upvotes: 0

Bharat Vankar
Bharat Vankar

Reputation: 327

Please follow below code. To find that characterssub contain by string or not. Hope this will work for you.

  • code
for(int i=0;i<9;i++){
    System.out.print("Enter your letter : ");
    char user_input_letter = enter.next().charAt(0);
    if(word_to_search.indexOf(user_input_letter)>=0){
        System.out.println("The letter exists !!");
    }
    else{
        System.out.println("This letter does not exist ! ");
    }
}

Upvotes: 1

Related Questions