Results 1 to 2 of 2
Thread: Need help with Hangman
- 08-16-2012, 09:38 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 24
- Rep Power
- 0
Need help with Hangman
I'm trying to make the letters that are in the word stay there after each iteration of the loop. This code just temporarily shows the letter in the word and then only shows the next letter you guess. Any ideas on how I can get them to stay or do I need to approach this entirely different?
Java Code:String str = "JAVA"; char[] array = str.toCharArray(); System.out.println(str); for (int i = 0; i < 6; i++) { String guess = scanner.nextLine().toUpperCase().trim(); char[] guessArray = guess.toCharArray(); for (int j = 0; j < array.length; j++) { if (guessArray[0] == array[j]) { System.out.print(guessArray[0]); } else { System.out.print("-"); } } }
- 08-18-2012, 05:32 AM #2
Member
- Join Date
- Nov 2011
- Posts
- 9
- Rep Power
- 0
Re: Need help with Hangman
Right now, your program is structured so that every time the user guesses, the output is generated based on the secret string and the single character that the user most recently entered. This provides no way of saving the letters the user has guessed previously. To fix this, you can add a new array, guessedChars[], that keeps track of this information. Here's how I would edit your program:
This will solve the problem you stated, but a few more remain. For example, it will only work with 4-character Strings - you'll have to change some things to generalize it to different lengths.Java Code:String str = "JAVA"; Scanner scanner = new Scanner(System.in); char[] array = str.toCharArray(); char[] guessedChars = new char[]{'-','-','-','-'}; System.out.println(str); for (int i = 0; i < 6; i++) { String guess = scanner.nextLine().toUpperCase().trim(); char[] guessArray = guess.toCharArray(); for (int j = 0; j < array.length; j++) { if (guessArray[0] == array[j]) { System.out.print(guessArray[0]); guessedChars[j] = array[j]; } else { System.out.print(guessedChars[j]); } } }
Similar Threads
-
Hangman with GUİ
By KSBeyaz in forum New To JavaReplies: 9Last Post: 11-20-2011, 06:45 PM -
hangman
By coltragon in forum New To JavaReplies: 2Last Post: 01-16-2010, 09:56 AM -
hangman
By javaMike in forum Advanced JavaReplies: 2Last Post: 11-14-2009, 09:06 AM -
Need help with Hangman!!!
By chinasome in forum New To JavaReplies: 10Last Post: 11-09-2008, 04:42 AM -
Hangman Help!!!
By chinasome in forum New To JavaReplies: 5Last Post: 11-08-2008, 02:30 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks