473,804 Members | 3,383 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

console hangman problem

94 New Member
I am trying to code a little console program (no swing, no awt, just console). But I am having some trouble and I am not sure if its my logic, or my code, or possibly both?!

Anyways heres what I currently have, I have not taken into consideration a user winning by guessing the word yet. Just working on displaying the hidden word and updating it with respect to the users guesses.

Expand|Select|Wrap|Line Numbers
  1. public class whatever {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         List<String> alpha = new ArrayList<String>(); //list of letters user can choose from
  6.         int maxTries = 7;
  7. //        final int maxWordLen = 25;
  8. //        int wrongGuesses = 0;
  9. //        int correctGuess;
  10. //        String guess;
  11.         String hiddenWord ="";
  12.         String correctChars= ""; // previously correctly guessed chars
  13.         String guessX = ""; // the new guess
  14.  
  15.  
  16.         String wordList [] = {"car", "desk"};
  17.         //select a word from array
  18.         int word = 0 + (int) (Math.random() * 2);
  19.  
  20.         String secretWord = wordList[word];
  21.  
  22.         for(int x = 0; x<secretWord.length(); x++)
  23.         {
  24.             hiddenWord += "-";
  25.         }
  26.         System.out.println("This is the hidden word: "+hiddenWord);
  27.  
  28.  
  29.         //System.out.println("The secret word is: "+secretWord);
  30.  
  31.  
  32.     //Add alphabet to list    
  33.         alpha.add("a");
  34.         alpha.add("b");
  35.         alpha.add("c");
  36.         alpha.add("d");
  37.         alpha.add("e");
  38.         alpha.add("f");
  39.         alpha.add("g");
  40.         alpha.add("h");
  41.         alpha.add("i");
  42.         alpha.add("j");
  43.         alpha.add("k");
  44.         alpha.add("l");
  45.         alpha.add("m");
  46.         alpha.add("n");
  47.         alpha.add("o");
  48.         alpha.add("p");
  49.         alpha.add("q");
  50.         alpha.add("r");
  51.         alpha.add("s");
  52.         alpha.add("t");
  53.         alpha.add("u");
  54.         alpha.add("v");
  55.         alpha.add("w");
  56.         alpha.add("x");
  57.         alpha.add("y");
  58.         alpha.add("z");
  59.  
  60.  
  61. //below here is good,kinda        
  62.         while(maxTries > 0 )
  63.         {
  64.  
  65.             System.out.println(hiddenWord);
  66.  
  67.             System.out.println("Here are your letters to chose from\n"+alpha);
  68.  
  69.             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  70.             System.out.println("Please make a guess: ");
  71.             try
  72.             {
  73.                 guessX = br.readLine();
  74.             } 
  75.             catch (IOException ioe) 
  76.             {
  77.                 System.out.println("IO error!");
  78.                 System.exit(1);
  79.             }
  80.  
  81. //            if in word use String newSecret and display correct letters
  82.             if(guessX.indexOf(secretWord)!= 0 )
  83.             {
  84.                 alpha.remove(guessX);
  85.                 String newSecret= secretWord.replaceAll("[^"+correctChars+guessX+"]", "-");
  86.                 hiddenWord = newSecret;
  87.                 System.out.println(hiddenWord);
  88.             }
  89.             else
  90.             {
  91.                 System.out.println("Sorry your guess is not in the word");
  92.                 maxTries --;
  93.             }
  94.             System.out.println("You have "+maxTries+" chances remaining");
  95.         }//while
  96.     }
  97. }
  98.  
I have viewed all of the threads revolving around this problem at this site and haven't been able to figure this out yet.

The output now will show: -e-- if the user entered e. But when it goes to the next line it is ----. Any thoughts?
Nov 8 '07 #1
11 3069
dav3
94 New Member
whoops

Expand|Select|Wrap|Line Numbers
  1. if(guessX.indexOf(secretWord)!= 0 )
  2.  
fixed that its now

Expand|Select|Wrap|Line Numbers
  1. if(secretWord.indexOf(guessX != -1)
  2.  
Nov 8 '07 #2
r035198x
13,262 MVP
whoops

Expand|Select|Wrap|Line Numbers
  1. if(guessX.indexOf(secretWord)!= 0 )
  2.  
fixed that its now

Expand|Select|Wrap|Line Numbers
  1. if(secretWord.indexOf(guessX != -1)
  2.  
Any reason why your alphabet is made up strings and not chars? Then you can add the alphabet to the list using a loop.
Nov 8 '07 #3
dav3
94 New Member
i knew how to add them easily (not eloquently) as strings. Is it incorrect to do it this way? Incorrect in such away that my program will fail, at this point design principles are not a concern. I can always refine once i have a working program.
Nov 8 '07 #4
r035198x
13,262 MVP
i knew how to add them easily (not eloquently) as strings. Is it incorrect to do it this way? Incorrect in such away that my program will fail, at this point design principles are not a concern. I can always refine once i have a working program.
In that case I'll reserve the rest of my comments.
Nov 8 '07 #5
dav3
94 New Member
In that case I'll reserve the rest of my comments.

Sorry if I offended you. I have made a very strong effort on this program, but am in need of help. I don't know why my newSecret word is only showing one correct letter at a time.


Ah wasnt adding to my correctChars variable. Problem solved.


Please do post your comments I am interested in becoming a better programmer, but when i spend hours coding something and have someone ask me about something that isnt the problem... i get defensive, sorry.
Nov 8 '07 #6
r035198x
13,262 MVP
Sorry if I offended you. I have made a very strong effort on this program, but am in need of help. I don't know why my newSecret word is only showing one correct letter at a time.


Ah wasnt adding to my correctChars variable. Problem solved.


Please do post your comments I am interested in becoming a better programmer, but when i spend hours coding something and have someone ask me about something that isnt the problem... i get defensive, sorry.
Shouldn't your while condition also test whether the word has now been guessed correctly or not?
Nov 8 '07 #7
JosAH
11,448 Recognized Expert MVP
Again: regular expressions are your friend here; suppose we have this:

Expand|Select|Wrap|Line Numbers
  1. String secretWord= "apple";
  2. String correctChars= "pe";
  3. String displayWord= secretWord.replaceAll("[^"+correctChars+"]", "-");
  4.  
a newChar is correct iff:

Expand|Select|Wrap|Line Numbers
  1. bool correct= secrectWord.indexOf(newChar) >= 0;
  2.  
The word has been guessed correctly iff:

Expand|Select|Wrap|Line Numbers
  1. bool guessed= displayWord.indexOf('-') < 0;
  2.  
kind regards,

Jos
Nov 8 '07 #8
r035198x
13,262 MVP
Again: regular expressions are your friend here; suppose we have this:

Expand|Select|Wrap|Line Numbers
  1. String secretWord= "apple";
  2. String correctChars= "pe";
  3. String displayWord= secretWord.replaceAll("[^"+correctChars+"]", "-");
  4.  
a newChar is correct iff:

Expand|Select|Wrap|Line Numbers
  1. bool correct= secrectWord.indexOf(newChar) >= 0;
  2.  
The word has been guessed correctly iff:

Expand|Select|Wrap|Line Numbers
  1. bool guessed= displayWord.indexOf('-') < 0;
  2.  
kind regards,

Jos
Which basically completes it.
I must say it was a very good effort from dav3.
Nov 8 '07 #9
JosAH
11,448 Recognized Expert MVP
Which basically completes it.
I must say it was a very good effort from dav3.
Yup, but if you use regular expressions the 'business logic' for this little game
doesn't need more than, say, 20 lines or so of code.

kind regards,

Jos
Nov 8 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
15802
by: tigrfire | last post by:
So I'm trying to write a hangman game and the output is coming out a little strange. Here's my code thus far: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int hangman()
18
9209
ilikepython
by: ilikepython | last post by:
Hi I'm new to Python(3 to 4 days) and I'm working on a hangman game and have been having some problems that really annoy me. Here is part of my script: c = input('Would you like to play hangman? Type y or n ') word = sample(('soccer', 'robbery', 'antibiotics'), 1) word = str(word) spaces = len(word) - 4 def hangman(): print '-------- '
4
2601
by: princessfrost | last post by:
Hi! I was wondering if someone could please help me with a hangman program that I have to do. I have some ideas, but really don't know what to do or where to start. My program needs to be: interactive with the user, menu based(like Menu: 1. Play hangman 2. Exit program), have a dictionaryand use a random method(create arrays of Strings or ListArray of Strings. e.g. : String dictionary = “apple”, “ball”, “cat”, “dog”, …..} minimum words...
47
11473
by: araujo2nd | last post by:
Originally Posted by araujo2nd my name is andre, im from south africa, i was wondering if any1 could help me with a hangman application, im now in grade 11 and have a huge portfolio piece to do by the 15th which i have just started now, i have always struggled with java and would rele appreciate all the help that i can get. Pls could some1 help me as much as u can, im nt asking u to do the program for me but if u could pls take me steps through...
2
4039
by: tesa | last post by:
I am not able to figure out how to make this work. I am trying to create a hangman game. I am in a basic javascripting class. I am to only use very basic code as you can see. I am able to use any online resources to help me. I have added alot of comments for what should be happening however is not happening. I also have a teacher that teaches us one way but then asks us to do things he has not taught. I am trying my very best. Any...
0
1694
by: Madmartigan | last post by:
Hi I'm a newbie to C# and have been instructed to create a Hangman game in SharpDevelop. I don't want the answer to the full code, just some help along the way. I have included my code thus far and at this stage would like to know how I can get the RandomWordManager, which I found on another site, to display a newly generated word as the textBox1 text when the user enters a new game. I have enclosed tags around the two forms I have...
8
3747
by: tidiz | last post by:
Hi, I'm trying to make a hangman game that should look like this: Welcome to Hangman ______ Your guess: c Success! __cc__ Your guess: b
1
2581
by: AlexSc | last post by:
Hi to All, I am doing on a hangman project, Where this is a very simple one, where player would guess the word and if it is correct the letter would be from "-" to the correct letter once all letter is correct they system will appear out good job u clear the game. I had done up the game and it work however i find mine is rather impractical, looking for better solution for it. please enlighten me in it. public static void...
0
9575
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10564
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10320
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10308
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7609
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.