I have created a program where you need to decode the word “program” however I am trying to detect when the user wins and matches all the letters, I am trying to display this but I am facing an issue where, even when all the letters in the word match a winning message is not displayed
my code
”’
public static void main( String[] args ) { String szDecryptedWord = "Encryptedword"; String szEncryptedWord = "1223567891234"; //creates char array for "$2%824*" char [] charArr = szEncryptedWord.toCharArray(); for(int i2 = 0; i2 < 10; i2++) { Scanner sc = new Scanner (System.in); System.out.println("Crack the enigma code (guess a letter) "+ szEncryptedWord + " :"); char someChar = sc.next().charAt(0); for(int i = 0; i < szDecryptedWord.length(); i++) { char DecryptedCharacter = szDecryptedWord.charAt(i); char encryptedCharacter = szEncryptedWord.charAt(i); if(someChar == DecryptedCharacter) { System.out.println("You have decoded the Character " + someChar + " Which was " + encryptedCharacter); } } //replace letter with encrypted word String szEncryptedWord = "$2%824*"; int indexOfLetter = szDecryptedWord.indexOf(someChar); //loop if index is positive or 0 while(indexOfLetter >= 0 ) { charArr[indexOfLetter] = szDecryptedWord.charAt(indexOfLetter); indexOfLetter = szDecryptedWord.indexOf(someChar, indexOfLetter +1); } szEncryptedWord = String.valueOf(charArr); System.out.println(szEncryptedWord); if(szEncryptedWord == "encryptedword") { System.out.println("you win!") } }
”’
Advertisement
Answer
Do not use the ==
operator to compare Strings. Use the equals(..)
method.
if ("PROGRAM".equals(szEncryptedWord)) ...
Strings are objects so using the ==
operator will check if they are the exact same object. This will work if you are pointing to the same String reference but may not if you are trying to compare two separate references.