Hello,
My group and I are currently writing a hangman-like program for our class (I know hangman related questions have been asked a billion times, but bear with me). We are having issues with being able to replace our * with the correct letter (if it is correct). Here is what we are using:
import java.util.Scanner;
public class HangmanMenu
{
static String word;
static char guess;
static int pos;
static String m;
static int tries;
public static void main(String[] args)
{
Instructions i = new Instructions();
Scanner keyBd = new Scanner( System.in );
char selection;
do{
System.out.println("\n--------------");
System.out.println("Main Menu\n");
System.out.println("1. Play");
System.out.println("2. Instructions");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
selection = keyBd.next().charAt(0);
switch (selection)
{
case '1':
word = Game.getWord();
m =Game.detNumLet();
//HERE IS WHERE THE PROBLEM IS
do
{
StringBuffer sb = new StringBuffer(m);
System.out.println();
System.out.println(m);
System.out.println("Guess a letter: ");
guess = keyBd.next().charAt(0);
pos = word.indexOf(guess);
if (pos>=0)
sb.setCharAt(pos, guess);
tries++;
//ignore this for now
if (m.equalsIgnoreCase(word))
break;
}while(tries<6);
break;
case '2':
i.run();
break;
case '3':
break;
default :
System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}
}
while( selection != '3');
}
}
Now, from what I understand, using the setCharAt method should take the guess and if it is in the word (pos>=0) it should take the guess and replace it at index pos, but it doesn't. This also doesn't work with double letters (such as the 2 c's in calculus) since it only returns the first index. We'll probably just make our words not have doubles unless anyone has suggestions on how to make this work.
Any help is greatly appreciated!