I am a beginner in java does not know much about it.
But to practise it I have tried to simulate the popular game Hangman
using simple methods.Please Guide me with the code

In this program the words are given by the user and then they are converted in to dashes.
Its like 2 player game
1st player enters the word or sentence and then seconds player tries to guess it.

but in this program the words entered by first player is displayed.How can I hide that words
after the first player had finished Entering the words. Also please help me to make this code more
like a working using minimum methods and objects.

    import java.util.*;
    import java.lang.String;
    import java.io.*;
    class Hangman {
        public static void main(String args[]) throws IOException {
            Scanner scan = new Scanner(System. in ); //Scanner method (Input)
            String s1 = new String(); //String Declartion Method
            DataInputStream in = new DataInputStream(System. in );
            int i, p = 1;
            do {
                //Ask input
                System.out.println("Enter Your Sentence\n");

                //Scan input in string "s1"
                s1 = scan.nextLine();

                //Display input
                System.out.println("\n" + s1 + "\n");

                //Trim
                s1 = s1.trim();

                //Covert lower
                s1 = s1.toLowerCase();

                //Extract the Str length
                int n = s1.length();

                //Copies string to arrays "s2"&"S3"
                char s2[] = new char[n];
                char s3[] = new char[n];
                s2 = s1.toCharArray();
                s3 = s1.toCharArray();

                //Generates a Random Number for hiding letters
                int randomInt = (int)(n * Math.random());
                while (randomInt == 0) {
                    randomInt = (int)(n * Math.random());
                }
    /*
    Display all the letters of strings stored in s2 array
    for(i=0;i<n;i++){
    System.out.println(s2[i]+":"+(i+1));
    }
    System.out.println("\n\n");
    */
                //Hidding characters and storing their location in Location array

                int location[] = new int[randomInt];
                for (i = 0; i < randomInt; i++) {
                    int arrayrandomInt = (int)(n * Math.random());
                    location[i] = arrayrandomInt;
                    s2[arrayrandomInt] = '_';
                }

                //Displays the Hangman sequence
                System.out.println("\n\nYour Game:\t\tLives:3\n");
                for (i = 0; i < n; i++) {
                    System.out.print(s2[i] + " ");
                }
                //Gives Info of total hidden letters
                System.out.println("\n\nHidding " + randomInt + " spaces out of " + n + "spaces\n");

                //Displays the Location Number of hidden characters
                System.out.println("\nWords hidden at Location ");
                for (i = 0; i < randomInt; i++) {
                    System.out.print((location[i] + 1) + "  ");
                }
                int count = randomInt;
                int lives = 3;
                int flag = 0;
                int total=0;
                /////////////////////////////////////////////////////////////////

                do {
                    do {

                        System.out.println("\nEnter the position of character: ");
                        p = scan.nextInt();
                        p = p - 1;

                        for (i = 0; i < randomInt; i++) {
                            if (p == location[i]) {
                                flag = 1;
                                break;
                            } else {
                                flag = 0;
                            }
                        }
                        if (flag == 0) {
                            System.out.println("ERR..ERROR..There is no hidden character at \n Position " + (p + 1) + "Please try again");
                        }
                    } while (flag != 1);
                    flag = 0;


                    String b1 = new String();
                    ///////////////////////////////////////////////////////////////////
                    while (flag != 1) {

                        System.out.println("\nEnter Your character: ");
                        b1 = in .readLine();
                        char a1 = s3[p];
                        char a2 = b1.charAt(0);
                        //System.out.println("a1="+a1+"\na2="+a2);
                        if (a1 == a2) {
                            s2[p] = a2;
                            flag = 1;
                            count--;
                            total=total+10;
                            System.out.print("Count=" + count);
                        } else {
                            flag = 0;
                        }
                        if (flag == 0) {
                            lives = lives - 1;
                            total=total-10;
                            System.out.println("Oops! you are wrong Please try again");
                            System.out.println("*********Lives Left:" + lives + "**********");
                        }
                        if (lives == 0) {
                            break;
                        }
                    }
                    if (flag == 1) {
                        System.out.print("Great Well Done\n\n");
                        for (i = 0; i < n; i++) {
                            System.out.print(s2[i] + " ");
                        }
                    }
                } while (lives != 0 && count > 0);
                if (lives == 0 || count < 0) {
                    System.out.println("Sorry you lost Answer was\n\n");
                    System.out.println(s1);
                    System.out.print("Total score"+total);
                } else {
                    System.out.print("Congrats\n\n");
                    System.out.print("Total score"+total);
                }
                p = 1;
                System.out.print("Want to play again\n\n");
                p = scan.nextInt();
                if (p == 1) {
                    continue;
                } else {
                    break;
                }
            } while (p == 1);
        }
    }

Recommended Answers

All 3 Replies

Here is some (random) feedback on your program:
There's not much wrong with that code really. This application is very small, and doesn't have much need for multiple classes or objects.

You comment lines 11-27 with comments that add zero information to the code that follows, but then you have great chunks of opaque logic like lines 75-150 where there are no comments to explain what is going on.
You should write comments for a reader who knows Java, but doesn't know your application. There's no need to explain Java syntax or common methods. Blocks of code like those on lines 80-89 need a comment at the beginning to explain what they are all about - having read that section again I still have no idea what it is trying to achieve. (Even better, use lots of methods with self-evident names, see below.)

You use integer "flag" variables where a boolean would be better.

You should give your variables and methods meaningful names - eg "flag" and "p" have no meaning at all. Instead of "p" you could call it "playAgain" and then lines like
if (p==1) {continue;} // what is the purpose of that??? What other values can that int have?
will become
if (playAgain) {continue;} // boolean variable, meaning is obvious

A pair of nested loops 75 lines long is too long to be understood. Break it up into a number of methods with self-documenting names so it becomes obvious, eg

do {
   setUpGame();
   do {
      getUserInput();
      checkForCorrectAnswers();
      displayResults();
   } while (! gameIsFinished);
   askUserPlayAgain();
} while (playAgain);

(Don't follow that blindly, I just made it up to make a point...)

Finally - hiding input on the console isn't easy. Simplest thing may just be to print 20 blank lines so the input is scrolled up out of view. Otherwize you can find some libraries on the web to give you more control over clearing the console etc than standard Java gives you.

I have written the comments for the last two loops hope this will help

    import java.util.*;
    import java.lang.String;
    import java.io.*;
    class Hangman {
        public static void main(String args[]) throws IOException {
            Scanner scan = new Scanner(System. in ); //Scanner method (Input)
            String s1 = new String(); //String Declartion Method
            DataInputStream in = new DataInputStream(System. in );
            int i, p = 1;
            do {
                //Ask input
                System.out.println("Enter Your Sentence\n");

                //Scan input in string "s1"
                s1 = scan.nextLine();

                //Display input
                System.out.println("\n" + s1 + "\n");

                //Trim
                s1 = s1.trim();

                //Covert lower
                s1 = s1.toLowerCase();

                //Extract the Str length
                int n = s1.length();

                //Copies string to arrays "s2"&"S3"
                char s2[] = new char[n];
                char s3[] = new char[n];
                s2 = s1.toCharArray();
                s3 = s1.toCharArray();

                //Generates a Random Number for hiding letters
                int randomInt = (int)(n * Math.random());
                while (randomInt == 0) {
                    randomInt = (int)(n * Math.random());
                }
    /*
    Display all the letters of strings stored in s2 array
    for(i=0;i<n;i++){
    System.out.println(s2[i]+":"+(i+1));
    }
    System.out.println("\n\n");
    */
                //Hidding characters and storing their location in Location array

                int location[] = new int[randomInt];
                for (i = 0; i < randomInt; i++) {
                    int arrayrandomInt = (int)(n * Math.random());
                    location[i] = arrayrandomInt;
                    s2[arrayrandomInt] = '_';
                }

                //Displays the Hangman sequence
                System.out.println("\n\nYour Game:\t\tLives:3\n");
                for (i = 0; i < n; i++) {
                    System.out.print(s2[i] + " ");
                }
                //Gives Info of total hidden letters
                System.out.println("\n\nHidding " + randomInt + " spaces out of " + n + "spaces\n");

                //Displays the Location Number of hidden characters
                System.out.println("\nWords hidden at Location ");
                for (i = 0; i < randomInt; i++) {
                    System.out.print((location[i] + 1) + "  ");
                }
                int count = randomInt;
                int lives = 3;
                int flag = 0;
                int total=0;
                /////////////////////////////////////////////////////////////////

                do {

                //this loop prepares the ask the user to input the positions number of the hidden character if it is correct
                //then it will proceed to ask for the character hidden at that position or else it will display error message that there 
                // is no hidden character at that position
                // Example :The generated hangman sequence is displayed with the character hidden and their position 
                //  String:-TITANIC
                //  Hangman sequence:-
                //  output:
                //  T _ T _ N _ C 
                //  0 1 2 3 4 5 6
                //
                //  Character hidden are at position 1,3,5 If the user enter number from these then it will proceed marking flag and then ask to
                //  guess the character at that position .But if it is wrong it will be marked flag 0 and then error message will be displayed.

                    do {

                        System.out.println("\nEnter the position of character: ");
                        p = scan.nextInt();
                        p = p - 1;

                        for (i = 0; i < randomInt; i++) {
                            if (p == location[i]) {
                                flag = 1;
                                break;
                            } else {
                                flag = 0;
                            }
                        }
                        if (flag == 0) {
                            System.out.println("ERR..ERROR..There is no hidden character at \n Position " + (p + 1) + "Please try again");
                        }
                    } while (flag != 1);
                    flag = 0;


                    String b1 = new String();

                    /*Whereas in this loop after inputing the corect postion of the hidden character the user had to insert correct hidden character after
                    which it will be compared with the original string s2 if correct A congration message will be displayed .After every correct input the
                    counter "count" be will be decreses by one which is indicating the number of hidden character left.BUt if wrong input is inserted lives
                    is decresed by one till it reach to zero as soon it reaches zero He will be greated with a message "Sorry you lost displaying the correct
                    answer"
                    */
                    while (flag != 1) {

                        System.out.println("\nEnter Your character: ");
                        b1 = in .readLine();
                        char a1 = s3[p];
                        char a2 = b1.charAt(0);
                        //System.out.println("a1="+a1+"\na2="+a2);
                        if (a1 == a2) {             //compares the user input with the original character present in the array s2
                            s2[p] = a2;
                            flag = 1;
                            count--;               //decrease the hidden character count by 1
                            total=total+10;
                            System.out.print("Count=" + count); //counts the number of hidden  character left
                        } else {
                            flag = 0;
                        }
                        if (flag == 0) {
                            lives = lives - 1;      //decrease lives counter by 1
                            total=total-10;
                            System.out.println("Oops! you are wrong Please try again");
                            System.out.println("*********Lives Left:" + lives + "**********");
                        }
                        if (lives == 0) {
                            break;
                        }
                    }
                    if (flag == 1) {
                        System.out.print("Great Well Done\n\n");
                        for (i = 0; i < n; i++) {
                            System.out.print(s2[i] + " ");
                        }
                    }
                } while (lives != 0 && count > 0);








                if (lives == 0 || count < 0) {             //compares with the counter or lives 
                    System.out.println("Sorry you lost Answer was\n\n");
                    System.out.println(s1);
                    System.out.print("Total score"+total);
                } else {
                    System.out.print("Congrats\n\n");
                    System.out.print("Total score"+total);
                }
                p = 1;
                System.out.print("Want to play again\n\n");
                p = scan.nextInt();
                if (p == 1) {
                    continue;
                } else {
                    break;
                }
            } while (p == 1);
        }
    }

That certainly helps a lot in understanding your code. But before writing more comments, ask yourself why the code isn't obvious - the answer is usually in the names you chose, eg

count--;               //decrease the hidden character count by 1 - comment needed because count could be anything

but...

hiddenCharacterCount--;  // needs no comment (reader knows what -- does)
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.