Issue
So for my computer programming course we were asked to create a basic word guess game and I am wondering why my program is not out putting the characters if they are guessed and are in the secret word. Here's what I have currently:
public static void main(String[] args) {
String sW = "";
int numG = 0;
String flag = "!";
String wordSF = "", updatedW = "";
String charG, wordG = "";
int num1 = (int) (20 * Math.random() + 1);
switch (num1) {
case 1:
if (num1 == 1) {
sW = "soup";
}
break;
case 2:
if (num1 == 2) {
sW = "money";
}
break;
case 3:
if (num1 == 3) {
sW = "brain";
}
break;
case 4:
if (num1 == 4) {
sW = "colour";
}
break;
case 5:
if (num1 == 5) {
sW = "batman";
}
break;
case 6:
if (num1 == 6) {
sW = "design";
}
break;
case 7:
if (num1 == 7) {
sW = "media";
}
break;
case 8:
if (num1 == 8) {
sW = "computer";
}
break;
case 9:
if (num1 == 9) {
sW = "monitor";
}
break;
case 10:
if (num1 == 10) {
sW = "password";
}
break;
case 11:
if (num1 == 11) {
sW = "textbook";
}
break;
case 12:
if (num1 == 12) {
sW = "mountain";
}
break;
case 13:
if (num1 == 13) {
sW = "sweater";
}
break;
case 14:
if (num1 == 14) {
sW = "darkness";
}
break;
case 15:
if (num1 == 15) {
sW = "flood";
}
break;
case 16:
if (num1 == 16) {
sW = "plastic";
}
break;
case 17:
if (num1 == 17) {
sW = "elephant";
}
break;
case 18:
if (num1 == 18) {
sW = "cabinet";
}
break;
case 19:
if (num1 == 19) {
sW = "speaker";
}
break;
case 20:
if (num1 == 20) {
sW = "electronic";
}
break;
}
Scanner input = new Scanner(System.in);
for (int i = 0; i < sW.length(); i++) {
wordSF += "-";
}
System.out.println(wordSF + "\n");
do {
System.out.print("Enter a letter or ! to guess the word");
charG = input.nextLine();
charG = charG.toUpperCase();
numG++;
if (sW.contains(charG)) {
updatedW = wordSF.substring(0, sW.indexOf(charG));
updatedW += charG;
updatedW += wordSF.substring(sW.indexOf(charG) + 1, wordSF.length());
wordSF = updatedW;
}
System.out.println(wordSF + "\n");
} while (!charG.equals(flag) && !wordSF.equals(sW));
if (charG.equals(flag)) {
System.out.println("What is your guess? ");
wordG = input.nextLine();
wordG = wordG.toUpperCase();
}
if (wordG.equals(sW) || wordSF.equals(sW)) {
System.out.println("You won");
} else {
System.out.println("you lost");
}
System.out.println("The secret word is " + sW);
System.out.println("You made " + numG + " guesses.");
// TODO code application logic here
}
}
Solution
In this piece of code, you have toUpperCase(). All of your words are in lower case. An upper case letter will not be found in a lower case word because they are different ASCII values. If you change it to toLowerCase(), then it will fill.
charG = input.nextLine();
charG = charG.toLowerCase();
numG++;
if (sW.contains(charG)) {
updatedW = wordSF.substring(0, sW.indexOf(charG));
updatedW += charG;
updatedW += wordSF.substring(sW.indexOf(charG) + 1, wordSF.length());
wordSF = updatedW;
}
Answered By - ProgrammersBlock