0

I getting the wrong result every time I run this program and I feel like an extra pair of eyes would be helpful at 4 in the morning. Can someone please help find where my curly braces or parentheses are off because I cannot find it for the life of me.

System.out.println("Please enter your guess") ;
    userGuess = kbd.next() ;
    if( userGuess != "a" || userGuess != "b" || userGuess != "c" || 
        userGuess != "d" || userGuess != "e" || userGuess != "f" || userGuess != "g" ||
        userGuess != "h" || userGuess != "i" || userGuess != "j" || userGuess != "k" ||
        userGuess != "l" || userGuess != "m" || userGuess != "n" || userGuess != "o" || 
        userGuess != "p" || userGuess != "q" || userGuess != "r" || userGuess != "s" || 
        userGuess != "t" || userGuess != "u" || userGuess != "v" || userGuess != "w" || 
        userGuess != "x" || userGuess != "y" || userGuess != "z" ||  userGuess!= "A" || 
        userGuess != "B" || userGuess != "C" || userGuess != "D" || userGuess != "E" || 
        userGuess != "F" || userGuess != "G" ||userGuess  != "H" || userGuess != "I" || 
        userGuess != "J" || userGuess != "K" ||userGuess  != "L" || userGuess != "M" || 
        userGuess != "N" || userGuess != "O" || userGuess != "P" || userGuess != "Q" || 
        userGuess != "R" || userGuess != "S" || userGuess != "T" || userGuess != "U" || 
        userGuess != "V" || userGuess != "W" || userGuess != "X" || userGuess != "Y" || 
        userGuess != "Z" ) {
        System.out.println("Invalid character, please enter your guess") ;
    }userGuess = kbd.next() ;

2 Answers2

1

Strings should be compared with the .equals() method and not ==.

That being said, in your case you might want to take a look at regular expressions, which would allow you to do a clean validation of the input. So in short:

//This code is untested, but it should guide you to what you need to do
Pattern userInput = Pattern.compile("^[A-Za-z]$");   //A-Z will match all the characters ranging from A to Z. a-z will do the same but it will check the lower case range. Alternatively, you could use ^[a-z]/i$ to make your regular expression case insensitive.
Scanner kbd = new Scanner(System.in);
String input = kbd.next();
Matcher matcher = userInput.matcher(input);
if(!matcher.matches())
{
    System.out.println("Invalid character, please enter your guess") ;
}
npinti
  • 51,780
  • 5
  • 72
  • 96
0

You need to change == to equals to compare values of String (and any other object).

Also you have problem with logic, because userGuess != "a" || userGuess != "b" is true for all characters since if something is a then it is not b so one of these conditions will be always true.

You may want to change || to && or use proper tools like regex, or methods from Character class like Character.isLetter.

Pshemo
  • 122,468
  • 25
  • 185
  • 269