I'm trying to write a program that lets the user play hangman in java. My code so far is:
I made some pseudocode, and i know how i want the program to work (though i'm sure there are more efficient ways of doing it). My problem is line 10 and 12, where i need to convert an int value into char. The reason why i do this is because of line 22, where i want to swap the asterisk for the correctly guessed letter. Any tips?
Don't put everything in the main method. Divide the different responsibilities over different classes and methods. For instance, you can have a Hangman class that knows the complete phrase, and keeps track of the letters that the user guessed. Design before you implement. Here's an example:
As for how to keep track of the progress, I recommend storing the masked word in a StringBuilder, and whenever the user makes a guess, you find the indices of that letter in the original phrase and then replace the mask in the StringBuilder at those indices with the guessed letter.
Thank you for replying. I still haven't learned about object oriented programming yet, i'm working on arrays now, and will move on to that once i feel ready. Therefore i would prefer not to use stringbuilder. What i need to understand with the current "tools" i got is how i can get this program to work. I know i should not cram too much logic into my main method, but my goal here is to understand manipulation of arrays, so i prefer to focus on that.
Let me put my question in a different way: Look at line 10. That gives a simple int value for deciding where in the string the letter gussed correctly is by using line 21. I would like my char value in line 12 to always show the same value as letterPosition. Basicly, char guessedLetter = int letterPosition.
There are several issues with your current approach. String.replace(char,char) replaces every occurrence of one character with another character. However, you're passing it a char and a string. This method overload doesn't exist.
String.charAt() returns the character at a given index in the string. You're doing exactly the opposite: You're passing it a character, and I think you're hoping to get an index back.
In the mean time, guessedLetter is never updated. If you want to know what character was guessed, you'll have to assign the value to the variable inside the while loop, not before it. However, I'm not convinced you need guessedLetter because of the problems I described earlier: You're using String.replace() and String.charAt() wrongly.
If this is an exercise in using arrays, then stop using String, and use a char, so you can easily iterate over it and replace characters as you go. Otherwise, use a StringBuilder. String is not well suited to handle mutations.
I would also recommend that you start easy by allowing a user to only guess one letter at a time, and not parts of words.