Skip to main content

Java Code for Hangman Game

import java.util.Arrays;
import java.util.Scanner;

public class Hangman{
    public static void main(String[] args) {
        String[] words = {"writer", "that", "program"};
        // Pick random index of words array
        int randomWordNumber = (int) (Math.random() * words.length);
        // Create an array to store already entered letters
        char[] enteredLetters = new char[words[randomWordNumber].length()];
        int triesCount = 0;
        boolean wordIsGuessed = false;
        do {
        // infinitely iterate through cycle as long as enterLetter returns true
        // if enterLetter returns false that means user guessed all the letters
        // in the word e. g. no asterisks were printed by printWord
        switch (enterLetter(words[randomWordNumber], enteredLetters)) {
            case 0:
                triesCount++;
                break;
            case 1:
                triesCount++;
                break;
            case 2:
                break;
            case 3:
                wordIsGuessed = true;
                break;
        }
        } while (! wordIsGuessed);
        System.out.println("\nThe word is " + words[randomWordNumber] +
            " You missed " + (triesCount -findEmptyPosition(enteredLetters)) +
            " time(s)");
    }

    /* Hint user to enter a guess letter,
    returns 0 if letter entered is not in the word (counts as try),
    returns 1 if letter were entered 1st time (counts as try),
    returns 2 if already guessed letter was REentered,
    returns 3 if all letters were guessed */
    public static int enterLetter(String word, char[] enteredLetters)    {
        System.out.print("(Guess) Enter a letter in word ");
        // If-clause is true if no asterisks were printed so
        // word is successfully guessed
        if (! printWord(word, enteredLetters))
            return 3;
        System.out.print(" > ");
        Scanner input = new Scanner(System.in);
        int emptyPosition = findEmptyPosition(enteredLetters);
        char userInput = input.nextLine().charAt(0);
        if (inEnteredLetters(userInput, enteredLetters)) {
            System.out.println(userInput + " is already in the word");
            return 2;
        }
        else if (word.contains(String.valueOf(userInput))) {
            enteredLetters[emptyPosition] = userInput;
            return 1;
        }
        else {
            System.out.println(userInput + " is not in the word");
            return 0;
            }
    }

    /* Print word with asterisks for hidden letters, returns true if
    asterisks were printed, otherwise return false */
    public static boolean printWord(String word, char[] enteredLetters) {
        // Iterate through all letters in word
        boolean asteriskPrinted = false;
        for (int i = 0; i < word.length(); i++) {
            char letter = word.charAt(i);
            // Check if letter already have been entered bu user before
            if (inEnteredLetters(letter, enteredLetters))
                System.out.print(letter); // If yes - print it
            else {
                System.out.print('*');
                asteriskPrinted = true;
            }
        }
        return asteriskPrinted;
    }

    /* Check if letter is in enteredLetters array */
    public static boolean inEnteredLetters(char letter, char[] enteredLetters) {
        return new String(enteredLetters).contains(String.valueOf(letter));
    }

    /* Find first empty position in array of entered letters (one with code \u0000) */
    public static int findEmptyPosition(char[] enteredLetters) {
        int i = 0;
        while (enteredLetters[i] != '\u0000') i++;
        return i;
    }
}

Comments

Popular posts from this blog

Banking (ICSE Class 10 Mathematics Project)

BANK ACCOUNT A bank account is a financial account between a bank customer and a financial institution. A bank account can be a deposit account, a credit card, or any other type of account offered by a financial institution. The financial transactions which have occurred within a given period of time on a bank account are reported to the customer on a bank statement and the balance of the account at any point in time is the financial position of the customer with the institution. a fund that a customer has entrusted to a bank and from which the customer can make withdrawals. BANK A bank is a financial institution and a financial intermediary that accepts deposits and channels those deposits into lending activities, either directly by loaning or indirectly through capital markets. A bank links together customers that have capital deficits and customers with capital surplu...

WALL OF THORAX-Anatomy Notes

1 WALL OF THORAX DESCRIBE COURSE, BRANCHES AND DISTRIBUTION OF TYPICAL INTERCOSTAL NERVE (LE). There are 12 thoracic spinal nerves. The 3 rd  to 6th nerves lie in typical intercostal spaces between typical ribs. They are confined to the thoracic wall. Formation: The thoracic spinal nerve is formed by anterior and posterior roots, which arises from the anterior and posterior horns of spinal cord respectively. The anterior and posterior roots join together to form the trunk. The trunk divides into anterior and posterior rami. The anterior ramus forms the intercostal nerve. Course: The nerve passes through the respective intervertebral foramen and appears in the posterior part of the intercostal spaces. On reaching the angle of the upper rib, the trunk of the nerve passes forwards along the costal groove between intercostalis internus and intimus muscle. Intercostal nerves runs in the costal groove and ends near the sternum. 2 In the costal groove...

KARYOTYPE

 A karyotype refers to a full set of chromosomes from an individual arranged according to length, position of centromere, banding pattern.  Karyotype is written as total number of chromosomes followed by sex chromosomes  Normal male karyotype: 46,XY, normal female karyotype: 46,XX  Chromosomes are classified into 7 groups and pasted accordingly- Group A- 1, 2, 3; group B- 4, 5; group C- 6-12, X; group D- 13, 14, 15; group E- 16, 17, 18; group F- 19, 20; group G- 21, 22, Y