Java Hangman

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 2207 Views - Last Post: 03 December 2012 - 12:54 AM Rate Topic: -----

#1 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Java Hangman

Posted 02 December 2012 - 09:52 PM

Hey guys, first off I want to say that I am very new to java and programming in general. I am a junior in HS in my CS1 class and we haven't exactly covered advanced methods of doing things. As you can see by the title, the project we are working on is hangman. The only rules for the project are that we must have a user make up a word and input it into the password field. Then we just give the use 8 tries to guess the word. I have tried looking for examples, but all of those consist of people using text documents containing a list a words. Mine, on the other hand, has a user enter a word. Also, I know that this code is extremely crude as I not know a whole lot.

Here is my code

import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import java.util.Scanner;
public class Hangman_New
{
    public static void main(String[] args)
    {
        String secretWord = "";
        Scanner scan = new Scanner(System.in);

        String m0 = ("      __________\n     |         |\n     |         |\n               |\n               |\n               |\n               |\n               |\n               |\n__________________________");
        String m1 = ("      __________\n     |         |\n     |         |\n     o         |\n               |\n               |\n               |\n               |\n               |\n__________________________");
        String m2 = ("      __________\n     |         |\n     |         |\n     o         |\n     |         |\n               |\n               |\n               |\n               |\n__________________________");
        String m3 = ("      __________\n     |         |\n     |         |\n     o         |\n    \\|         |\n               |\n               |\n               |\n               |\n__________________________");
        String m4 = ("      __________\n     |         |\n     |         |\n     o         |\n    \\|/        |\n               |\n               |\n               |\n               |\n__________________________");
        String m5 = ("      __________\n     |         |\n     |         |\n     o         |\n    \\|/        |\n     |         |\n               |\n               |\n               |\n__________________________");
        String m6 = ("      __________\n     |         |\n     |         |\n     o         |\n    \\|/        |\n     |         |\n    /          |\n               |\n               |\n__________________________");
        String m7 = ("      __________\n     |         |\n     |         |\n     o         |\n    \\|/        |\n     |         |\n    / \\        |\n               |\n               |\n__________________________");

        JPasswordField passField = new JPasswordField();
        int userChoice = JOptionPane.showConfirmDialog(
                null, passField, "Enter your secret word:", 
                JOptionPane.OK_CANCEL_OPTION);

        if (userChoice == JOptionPane.OK_OPTION)
        {
            secretWord = new String(passField.getPassword());
            System.out.println("Your secret word was: \"" + secretWord + "\"");
        }
        else;

        System.out.print("Choose your first letter: ");
        String firstLetter = scan.nextLine();

        if(secretWord.contains(firstLetter))
        {
            System.out.println(m0);
        }
        else;
        {
            System.out.println(m1);
        } 

        System.out.print("Choose your second letter: ");
        String secondLetter = scan.nextLine();

        if (secretWord.contains(secondLetter))
        {
            if (secretWord.contains(firstLetter))
            {
                System.out.println(m0);
            }
            else;
            {
                System.out.println(m1);
            }
        }
        else;
        {
            if (secretWord.contains(firstLetter))
            {
                System.out.println(m1);
            }
            else;
            {
                System.out.println(m2);
            }
        }

        System.out.print("Choose your third letter: ");
        String thirdLetter = scan.nextLine();

        if (secretWord.contains(thirdLetter))
        {
            if (secretWord.contains(secondLetter))
            {
                if (secretWord.contains(firstLetter))
                {
                    System.out.println(m0);
                }
                else;
                {
                    System.out.println(m1);
                }
            }
            else;
            {
                System.out.println(m1);
            }
        }
        else;
    }
}


I thought that I was doing well until I couldn't find a way to check to see if the entered letter was in the secret word that was entered at the beginning. I tried things like secretWord.contains() and secretWord.indexof() but couldn't find a solution.

If someone could point me in the right direction, that would be greatly appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Java Hangman

#2 ladyaoi   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 87
  • Joined: 22-September 11

Re: Java Hangman

Posted 02 December 2012 - 10:09 PM

when you say you have eight tries to guess the word, does this mean the word only has at most eight letters. Or the words can be an indefinite size but you can only make eight errors trying to guess the word?
Was This Post Helpful? 1
  • +
  • -

#3 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 10:12 PM

The word can have an indefinite size but you can only have eight guesses. This is mostly because of our limited knowledge of java.
Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11095
  • View blog
  • Posts: 18,982
  • Joined: 19-March 11

Re: Java Hangman

Posted 02 December 2012 - 10:24 PM

System.out.print("Choose your first letter: ");
String firstLetter = scan.nextLine();


Have you come across the concept of arrays yet? This style of coding is a real horror, as you've probably discovered already. If you can use an array, though, life gets a lot easier.
Was This Post Helpful? 0
  • +
  • -

#5 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 10:26 PM

Yeah, I know its a horror :P ....... But, to tell you the truth, we have not covered arrays at all.
Was This Post Helpful? 0
  • +
  • -

#6 ladyaoi   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 87
  • Joined: 22-September 11

Re: Java Hangman

Posted 02 December 2012 - 10:32 PM

Okay, my suggestion (and I'm still green at java too, so get a second opinion by all means) is to make the secret word an array. Each letter has its own index, and you can then compare the the guess to each index of the array. You will need 2 loops, the outer loop is a for statement that will track the number of incorrect guesses, the inner loop will compare the guess with the indexes of the array.

If you can't use an array, then you need to make the secret word a definite length. And set each letter of the secret word as a variable: lettterOne, letterTwo, etc... Then you can compare the guess to each variable. Do you know how to use switch statements?
Was This Post Helpful? 1
  • +
  • -

#7 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 10:36 PM

View Postladyaoi, on 02 December 2012 - 10:28 PM, said:

Okay, my suggestion (and I'm still green at java too, so get a second opinion by all means) is to make the secret word an array. Each letter has its own index, and you can then compare the the guess to each index of the array. You will need 2 loops, the outer loop is a for statement that will track the number of incorrect guesses, the inner loop will compare the guess with the indexes of the array.


That sounds like it would work, but, I feel as if it would be a bit strange for me to be using a concept that has not been covered in my class(arrays). Not to mention my teacher might find it a bit fishy as well.

View Postladyaoi, on 02 December 2012 - 10:32 PM, said:

Okay, my suggestion (and I'm still green at java too, so get a second opinion by all means) is to make the secret word an array. Each letter has its own index, and you can then compare the the guess to each index of the array. You will need 2 loops, the outer loop is a for statement that will track the number of incorrect guesses, the inner loop will compare the guess with the indexes of the array.

If you can't use an array, then you need to make the secret word a definite length. And set each letter of the secret word as a variable: lettterOne, letterTwo, etc... Then you can compare the guess to each variable. Do you know how to use switch statements?


We have not learned switch statements yet either.
Was This Post Helpful? 0
  • +
  • -

#8 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11095
  • View blog
  • Posts: 18,982
  • Joined: 19-March 11

Re: Java Hangman

Posted 02 December 2012 - 10:42 PM

Okay, you have two choices. One, you can do what your teacher says. It's going to be a real bastard of a thing, and really the only thing you can learn from it is that this sort of thing is a pain in the mumble. But on the other hand, you'll be doing what the teacher is looking for, and sometimes it's worth just giving them what they want.

Other choice, you can look up some stuff about arrays and try to get ahead of the game. Oracle has a good tutorial on the subject, which you should read through anyway - you're going to need this pretty soon, no matter what happens, so it can't hurt to learn it now.

However, the problem you're having now is not about arrays. It's here:


String firstLetter = scan.nextLine();


When you ask a Scanner object for nextLine(), it consumes up to the next linebreak character that it finds, and returns that with the String. So when you enter "s" for the first letter, the String firstLetter actually contains "s\n", that is, "s" followed by a newline character.
Look at the methods of the String class to find a way to get rid of this.


That should at least get you along towards where you need to be for this assignment.

This post has been edited by jon.kiparsky: 02 December 2012 - 10:43 PM

Was This Post Helpful? 0
  • +
  • -

#9 ladyaoi   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 87
  • Joined: 22-September 11

Re: Java Hangman

Posted 02 December 2012 - 10:44 PM

I started learning java in school as well. Here's the first lesson I learned the hard way...The java library/API is your best friend. There is nothing wrong with searching the library for a method or class that will meet your needs. No class can teach all of java, you have to have the incentive to go look.

You can do this program without a switch statement, but it will be tedious and redundant. This violates lesson number two I learned the hard way: Don't reinvent the wheel. Don't create long-winded code when there is an established way streamlined way to perform the same function.

Do what you feel is best, without the switch statement or a for loop, you need to code a comparison for guess1 through guess 8 for each secret word letter variable.
Was This Post Helpful? 1
  • +
  • -

#10 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 10:59 PM

Alright, I have decided to just take the redundant route as it seems simpler to preform with my knowledge at this point in time. However, I do have a couple questions. MY first question is how to go about splitting it. I looked at the API and found the split method but how would you go about splitting each individual letter of the secret word? My second question is i, after splitting the secret word, do I use the compareto method?

Quote

When you ask a Scanner object for nextLine(), it consumes up to the next linebreak character that it finds, and returns that with the String. So when you enter "s" for the first letter, the String firstLetter actually contains "s\n", that is, "s" followed by a newline character.
Look at the methods of the String class to find a way to get rid of this.


I'm looking at the string class in the API. But, i honestly don;t really know what i'm looking for. Am I trying to only look for the first character in the string? Or, am I trying to take off the "\n" in the string itself?
Was This Post Helpful? 0
  • +
  • -

#11 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11095
  • View blog
  • Posts: 18,982
  • Joined: 19-March 11

Re: Java Hangman

Posted 02 December 2012 - 11:03 PM

Falorion, listen to ladyaoi. There's a lot of sense there. Definitely a good idea to keep the API docs open for the classes you're working with. The core library methods should really be firmly stuck in your head before too long, and the only way that happens is constant review, and writing code with them. I would actually suggest that you sit down and write little programs to use each method of String, just so you know you've played with all of them. Do the same for other classes that you find yourself using regularly.


That's for later in the week though. Here's a thought for your current problem: is there any reason you're storing the input at all? After all, you only need it once, to check whether the secret word contains the user's guess. After that, there's no real need to hang on to it.

Are you familiar with loops yet? If so, you might think about it this way:

in a loop, 
  get input from the user
  if the secret contains the guess, increment a counter of correct guesses
  otherwise, increment a counter of incorrect guesses



How you get out of the loop will depend on what tools you have available to you, but this way you can at least save yourself a lot of repetitive typing.

You'll notice, of course, that there's a pretty big bug in this implementation. Can you spot it? Can you see a way around it? There are at least two ways to deal with it using just Strings and their methods.

There's also a bit of a problem with providing the user with the feedback about their guesses, since you don't have any loop-friendly data constructs to work with.

View PostFalorion, on 03 December 2012 - 12:59 AM, said:

I'm looking at the string class in the API. But, i honestly don;t really know what i'm looking for. Am I trying to only look for the first character in the string? Or, am I trying to take off the "\n" in the string itself?


Both approaches are reasonable, and there are methods to do both of those. From the way you ask the question, I think you're looking at two good methods for solving this. Either of them would be reasonable.
Was This Post Helpful? 0
  • +
  • -

#12 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 11:13 PM

View Postjon.kiparsky, on 02 December 2012 - 11:03 PM, said:

Falorion, listen to ladyaoi. There's a lot of sense there. Definitely a good idea to keep the API docs open for the classes you're working with. The core library methods should really be firmly stuck in your head before too long, and the only way that happens is constant review, and writing code with them. I would actually suggest that you sit down and write little programs to use each method of String, just so you know you've played with all of them. Do the same for other classes that you find yourself using regularly.


That's for later in the week though. Here's a thought for your current problem: is there any reason you're storing the input at all? After all, you only need it once, to check whether the secret word contains the user's guess. After that, there's no real need to hang on to it.

Are you familiar with loops yet? If so, you might think about it this way:

in a loop, 
  get input from the user
  if the secret contains the guess, increment a counter of correct guesses
  otherwise, increment a counter of incorrect guesses



How you get out of the loop will depend on what tools you have available to you, but this way you can at least save yourself a lot of repetitive typing.

You'll notice, of course, that there's a pretty big bug in this implementation. Can you spot it? Can you see a way around it? There are at least two ways to deal with it using just Strings and their methods.

There's also a bit of a problem with providing the user with the feedback about their guesses, since you don't have any loop-friendly data constructs to work with.

View PostFalorion, on 03 December 2012 - 12:59 AM, said:

I'm looking at the string class in the API. But, i honestly don;t really know what i'm looking for. Am I trying to only look for the first character in the string? Or, am I trying to take off the "\n" in the string itself?


Both approaches are reasonable, and there are methods to do both of those. From the way you ask the question, I think you're looking at two good methods for solving this. Either of them would be reasonable.


We have briefly covered the while loop and that sounds like a very good thing to use. Although I am still attempting to figure out the flaw in using loops, I do have one other question. How would I go about not storing the guesses? Do I just delete the "String firstLetter + "?
Was This Post Helpful? 0
  • +
  • -

#13 ladyaoi   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 87
  • Joined: 22-September 11

Re: Java Hangman

Posted 02 December 2012 - 11:16 PM

If want to be redundant, use the scanner to get individual letter input rather than full word. Check the API for a method that will take the token. Your code would be something like...
System.out.println("Type a five letter secret word.  Hit enter after each letter");
scanner.method()= secretLetter1;
scanner.method()= secretLetter2;
repeat until secretLetter5


This post has been edited by ladyaoi: 02 December 2012 - 11:17 PM

Was This Post Helpful? 0
  • +
  • -

#14 Falorion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 02-December 12

Re: Java Hangman

Posted 02 December 2012 - 11:21 PM

View Postladyaoi, on 02 December 2012 - 11:16 PM, said:

If want to be redundant, use the scanner to get individual letter input rather than full word. Check the API for a method that will take the token. Your code would be something like...
System.out.println("Type a five letter secret word.  Hit enter after each letter");
scanner.method()= secretLetter1;
scanner.method()= secretLetter2;
repeat until secretLetter5



Instead of doing that, is it possible that, since I am setting the max letter count to 8, I can just have the user eneter the full word then use sub strings to break it up?
Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11095
  • View blog
  • Posts: 18,982
  • Joined: 19-March 11

Re: Java Hangman

Posted 02 December 2012 - 11:54 PM

View PostFalorion, on 03 December 2012 - 01:21 AM, said:

View Postladyaoi, on 02 December 2012 - 11:16 PM, said:

If want to be redundant, use the scanner to get individual letter input rather than full word. Check the API for a method that will take the token. Your code would be something like...
System.out.println("Type a five letter secret word.  Hit enter after each letter");
scanner.method()= secretLetter1;
scanner.method()= secretLetter2;
repeat until secretLetter5



Instead of doing that, is it possible that, since I am setting the max letter count to 8, I can just have the user eneter the full word then use sub strings to break it up?


Better still, you could use String.toCharArray... oh, wait, nevermind. :)

No, I would get the secret word as one String and then use the charAt method to look at individual chars.
This is actually very close to working with arrays. In fact, the underlying representation of a String is actually an array of char, so you really are working with a sort of deviant wrapper on an array. But I bet your teacher will allow it.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2