Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Hangman {
- static String words[] = {"expression", "illegal", "query", "elaborate", "sunshine", "darkness", "stationary", "original", "confused", "superior"};
- static int x = ((int) (Math.random() * 10)), life = 7;
- static String word = words[x], word2, word3, name, chosen = "";
- static char letter;
- static void getword() {
- word2 = "";
- for (int i = 0; i < word.length(); i++) {
- word2 = word2 + '*';
- }
- System.out.println(" Welcome to HangMan. You start with 7 lives. You lose a live for every wrong letter. ");
- System.out.println(" The letters are: " + word2);
- }
- static void input() {
- System.out.println(" Enter any letter");
- letter = new Scanner(System.in).next().charAt(0);
- if (chosen.indexOf(letter) >= 0) {
- System.out.println("You have already chosen this letter. Please try again.");
- input();
- } else if (word.indexOf(letter) >= 0) {
- chosen = chosen + letter;
- correctLetter();
- } else {
- chosen = chosen + letter;
- wrongLetter();
- }
- }
- static void correctLetter() {
- word3 = "";
- for (int i = 0; i < word.length(); i++) {
- if (word.charAt(i) == letter) {
- word3 = word3 + letter;
- } else if (word2.charAt(i) == '*') {
- word3 = word3 + '*';
- } else {
- word3 = word3 + word2.charAt(i);
- }
- }
- word2 = word3;
- System.out.println(" You have guessed a correct letter. ");
- System.out.println(" The letters are: " + word2);
- finalcheck();
- }
- static void wrongLetter() {
- System.out.println(" You have chosen a wrong letter and so, you lose a life.");
- life--;
- System.out.println(life + " lives remaining.");
- System.out.println(" The letters are: " + word2);
- finalcheck();
- }
- static void finalcheck() {
- if (life == 0) {
- System.out.println(" You have lost all your lives and so, you lose the game. The correct word was '" + word + "' .");
- } else if (word2.indexOf('*') < 0) {
- System.out.println(" Congratulations, You guessed the correct word '" + word + "' and have won the game with " + life + " lives remaining.");
- } else {
- input();
- }
- }
- public static void main(String s[]) {
- getword();
- input();
- }
- }
Add Comment
Please, Sign In to add comment