Greetings from Greece.
We got a Hangman assignment for my Class at Java.
I m just a begginer.And the whole input/output thing is done either by console (system.out.println) or with JOptionPane.

So here is my code

import javax.swing.JOptionPane;
import java.util.*;


public class Hangman
{




	public static void main (String a [])
	{



					//////////////////

					String word = "";
					int guesses;

					//////////////////





					/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

					String difficulty = JOptionPane.showInputDialog ("Select difficulty : 1 for easy -- 2 for normal -- 3 for hard");
					int	intDifficulty = Integer.parseInt(difficulty);

					/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////






					/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

					String easyDictionary [] = { " abstraction ", " ambiguous ", " arithmetic ", " backslash " , " bitmap", " circumstance", " combination", " consequently", " consortium", " decrementing", " dependency", " disambiguate", " dynamic", " encapsulation", " equivalent", " expression", " facilitate", " fragment", " hexadecimal", " implementation", " indistinguishable", " inheritance", " internet", " java", " localization", " microprocessor", " navigation", " optimization", " parameter", " patrick", " pickle", " polymorphic", " rigorously", " simultaneously", " specification", " structure", " lexical", " likewise", " management", " manipulate", " mathematics", " hotjava", " vertex", " unsigned", " traditional" };


					String normalDictionary [] = {"boy", "girl", "mother", "father", "sister", "love", "sky", "wind", "water", "study", "ball",
					"cat", "dog", "puppy", "kitten", "apple", "pear", "lemon", "mango", "peach", "apricot", "chips", "steak", "fries", "cheese",
					"patatoe", "wedge", "heel", "hand", "foot", "arm", "leg", "nose", "face", "mouth", "tongue", "fingers", "toes", "line", "space",
					"phone", "cord", "core", "grass", "trees", "birds", "animals", "lazy", "funny", "king", "queen", "heart", "heat", "cold", "sun",
					"moon", "movie", "theater", "hairy", "big", "small", "large", "huge", "pig", "donkey", "cow", "chicken", "pizza", "bread", "stones",
					"sticks", "leaves", "letters", "alphabet", "soup", "hungry", "tired", "sleepy", "noisy", "caring", "friends", "month", "day", "light"};


					String hardDictionary [] = { "toothbrush", "savings", "bank", "account", "teller", "paper", "pencil", "tea", "coffee", "spirit", "ghost", "can", "melon", "necklace",
					"screen", "baloon", "string", "calendar", "work", "toys", "kids", "school", "class", "campus", "freedom", "liberty", "happiness",
					"university", "message", "marker", "crayon", "eraser", "music", "lyrics", "songs", "ballads", "shapes", "triangle", "circle", "rectangle",
					"square", "oval", "show", "video", "player", "team", "sport", "basketball", "football", "soccer", "softball", "baseball", "tennis",
					"hockey", "lacrosse", "volleyball", "circut", "blade", "scratch", "hit", "home", "house", "safe", "safety", "number", "count", "bear",
					"goose", "lama", "panda", "lion", "tiger", "cheetah", "computer", "crackers", "rice", "fan", "shoes", "book", "story", "princess",
					"prince", "jester", "court", "jury", "judge", "bench", "scandal", "name", "newspaper", "press", "shove", "tear", "cry", "magic", "tricks",
					"cereal", "breakfast", "lunch", "dinner", "main", "course", "fork", "spoon", "knife", "lamp", "desk", "bottle", "highlighter", "cap",
					"medicine", "six", "seven", "flower", "rose", "petal"};

					////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



					///////////////////////////////////////////////

					Scanner letterProvided = new Scanner(System.in);
					String pickedArray [] = {""};
					String letter;

					///////////////////////////////////////////////




				/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

				if (intDifficulty == 1 )
				{

					Collections.shuffle( Arrays.asList ( easyDictionary ));
					word = ( easyDictionary[1] );
					System.out.println( "Easy huh?" );

					
				}

				else if (intDifficulty == 2)
				{
					Collections.shuffle( Arrays.asList (normalDictionary ));
					word = ( normalDictionary[1] );
					System.out.println( "At last!A normal guy." );

					
				}
				else if (intDifficulty == 3)
				{
					Collections.shuffle( Arrays.asList ( hardDictionary ));
					word =( hardDictionary[1] );
					System.out.println ( "You think you are a tough guy?" );

				
				}
				else
				{
					JOptionPane.showMessageDialog( null,"ERROR TYPE #1: Please input 1 , 2  or 3 to select Hangman's difficulty!" , "Error!" ,JOptionPane.ERROR_MESSAGE );
				}

				/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



				///////////////////////////////////////////////

				String [] hidden = new String [word.length()];

				///////////////////////////////////////////////



				///////////////////////////////////////////////

				for ( int i = 0 ; i < word.length() ; i++ )
				{
					hidden[i] = "_";
				}

				///////////////////////////////////////////////



					/////////////////////////////////////////////////////////////
					System.out.print("Please enter a letter in lower case only!");
					letter = letterProvided.nextLine();
					
					
		



		}



}

I got some problems here.
First I need my word to be in an array so to check if the input is correct or not.With an array ill be able to check double letters also! So I just dont know what to do with the input I got from

System.out.print("Please enter a letter in lower case only!");
					letter = letterProvided.nextLine();

Secondly i need a counter about maximum Tries , but i cant figure out where i should put the loop and do

maximumTries--;

Thank you a lot for reading my post =)

Recommended Answers

All 12 Replies

First one piece of advice : Use Consistent indentation, Some places you have indented your code, at other places you have just forgotten or put extra tabs for no reason.

Following is the lin for Java SE 6 docs:- http://java.sun.com/javase/6/docs/api/

Make it a point to look there if first your need some functionality from some of Java's inbuilt classes, for ex: "String" class in this case.

Next use the charAt(int) method of the String class if you want to access each of the characters individually, just like an Array.

Thanks a lot.I ll study it a bit and come back to you with more questions if any :)

Ok here is my code now

import javax.swing.JOptionPane;
import java.util.*;
public class Hangman
{
    public static void main (String a [])
    {



                    String word = "";
                    int badGuesses;

                    String difficulty = JOptionPane.showInputDialog ("Select difficulty : 1 for easy -- 2 for normal -- 3 for hard");
                    int intDifficulty = Integer.parseInt(difficulty);


                    String dictionaries [][] = {

					                { 	" abstraction ", " ambiguous ", " arithmetic ", " backslash " , " bitmap", " circumstance", " combination", " consequently", " consortium",
					                    " decrementing", " dependency", " disambiguate", " dynamic", " encapsulation", " equivalent", " expression", " facilitate", " fragment",
					                    " hexadecimal", " implementation", " indistinguishable", " inheritance", " internet", " java", " localization", " microprocessor",
					                    " navigation", " optimization", " parameter", " patrick", " pickle", " polymorphic", " rigorously", " simultaneously", " specification",
					                    " structure", " lexical", " likewise", " management", " manipulate", " mathematics", " hotjava", " vertex", " unsigned", " traditional"
					                },


					                {	"boy", "girl", "mother", "father", "sister", "love", "sky", "wind", "water", "study", "ball",
					                    "cat", "dog", "puppy", "kitten", "apple", "pear", "lemon", "mango", "peach", "apricot", "chips", "steak", "fries", "cheese",
					                    "patatoe", "wedge", "heel", "hand", "foot", "arm", "leg", "nose", "face", "mouth", "tongue", "fingers", "toes", "line", "space",
					                    "phone", "cord", "core", "grass", "trees", "birds", "animals", "lazy", "funny", "king", "queen", "heart", "heat", "cold", "sun",
					                    "moon", "movie", "theater", "hairy", "big", "small", "large", "huge", "pig", "donkey", "cow", "chicken", "pizza", "bread", "stones",
					                    "sticks", "leaves", "letters", "alphabet", "soup", "hungry", "tired", "sleepy", "noisy", "caring", "friends", "month", "day", "light"
					                },


					                { "toothbrush", "savings", "bank", "account", "teller", "paper", "pencil", "tea", "coffee", "spirit", "ghost", "can", "melon", "necklace",
					                    "screen", "baloon", "string", "calendar", "work", "toys", "kids", "school", "class", "campus", "freedom", "liberty", "happiness",
					                    "university", "message", "marker", "crayon", "eraser", "music", "lyrics", "songs", "ballads", "shapes", "triangle", "circle", "rectangle",
					                    "square", "oval", "show", "video", "player", "team", "sport", "basketball", "football", "soccer", "softball", "baseball", "tennis",
					                    "hockey", "lacrosse", "volleyball", "circut", "blade", "scratch", "hit", "home", "house", "safe", "safety", "number", "count", "bear",
					                    "goose", "lama", "panda", "lion", "tiger", "cheetah", "computer", "crackers", "rice", "fan", "shoes", "book", "story", "princess",
					                    "prince", "jester", "court", "jury", "judge", "bench", "scandal", "name", "newspaper", "press", "shove", "tear", "cry", "magic", "tricks",
					                    "cereal", "breakfast", "lunch", "dinner", "main", "course", "fork", "spoon", "knife", "lamp", "desk", "bottle", "highlighter", "cap",
					                    "medicine", "six", "seven", "flower", "rose", "petal"
                }};

                      			if( intDifficulty > dictionaries.length )

				          		 {
				               			System.out.println( "Sorry answer between 1 and 3" );
				               			return;
       							 }



					String pickedArray[] = dictionaries[intDifficulty];
					String[] difficultyMsg = {"Easy huh?", "At last!A normal guy.", "You think you are a tough guy?"};
        			System.out.println( difficultyMsg[intDifficulty] );


                    Scanner letterProvided = new Scanner(System.in);
                    String pickedArray [] = {""};
                    String letter;

					word = pickedArray[0].trim();
					char[] hidden = new char[word.length()];


					for(int i = 0; i < word.length(); i++)
					{
           				 hidden[i] = '_';
					}

					char[] digit = word.toCharArray();
					Scanner letterProvided = new Scanner(System.in);



					badGuesses = 0;
					do
					{
						System.out.print("So far: " + badGuesses + "bad guesses");


						for(int i = 0; i < word.length(); i++)
						{
                			System.out.print(hidden[i]);
						}

						System.out.print( "\nPlease enter a letter: " );
						String letter = letterProvided.nextLine().toLowerCase();

						char guess = letter.charAt(0);
						boolean correctGuess = false;

						for(int i = 0; i < word.length(); i++)
						{
							if(guess == digit[i])
							{
								hidden[i] = guess;
								correctGuess = true;

							}
						}


						if(!correctGuess)
						{
							badGuesses++;
						}

						 while(badGuesses < 6);

the game runs properly but the only problem now is that i need the guessedletters to be printed.Thats an array full of the inputs i guess?
and if user inputs used letter not to count it as a badguess !

Now that I actually saw your code, you have actually reduced Java to the level of a Structured Programming Language, So in order to really design your applications better I suggest you go through this tutorial, for introducing you to the world of Object Oriented Programming.

Oh come on.
You were not born Programmer :)
So me neither.Thanks anyway.
I ve finished with it.Thank you a lot.

> Oh come on.
> You were not born Programmer

Sure he wasn't but I don't think this would have been his reply when pointed in the right direction. Of course it's a different thing if you were just trying to get over this assignment...

As you can read I didnt beg for code or something.And u didnt provide me with any anyway!
And i want to learn.If its Hangman game the way i will learn so be it.
Its not just an assignment.Its practice and experience

If you really want to learn then don't be so hostile to suggestions that could help you improve.
His point was that you shouldn't write all of your code in main(). Learn to use classes and methods properly, as that is the entire foundation of Java.

If he really wanted teach / advice / help he could do it in a not humiliating way (reduce java's level!)
And i just waited to complete the whole thing and then break it to methods so my main would just call methods that do stuff.
And ofc i read what Mr. stephen84s wrote and was very helpful.I thanked him bout that !
(')_(')
(='.'=)
(.)_(.)

If he really wanted teach / advice / help he could do it in a not humiliating way (reduce java's level!)

Now whats so humiliating in that ??? Such a big attitude from a guy seeking help, this absolutely ridiculous

*sigh* Good Luck at your lives =) And thnx again!Srsly =)

Have a look at the attachment.

Let me know if you have any questions.

cheers
M

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.