In: Computer Science
Write a program to allow a user to play the game Hangman. DO NOT USE AN ARRAY
The program will generate a random number (between 1 and 4581) to pick a word from the file - this is the word you then have to guess.
Note: if the random number you generate is 42, you need the 42nd word - so loop 41 times picking up the word from the file and not doing anything with it, it is the 42nd you need. Here is how you will do this:
String word:
for (int k=0; k<41; k++)
{word=scnr.nextLine();
}//end loop and now pick up the word you want
word=scnr.nextLine() //this is the one you want
The user will be allowed to guess a letter as many times as it takes - but 10 wrong guesses and they lose!!
Eventually either they won or lost. In case they lost print out the answer.
Code language: Java using JGrasp or NetBeans
import java.util.Scanner;
import java.util.Random;
import java.io.*;
// class defination
class Hangman
{
// main function
public static void main(String[] args)
{
// variable declaration
Random random = new Random();
String word = new String();
int wrongCount = 0;
// game will run until user wants
to exit or made 10 wrong guesses
while(true)
{
// ask user for
option weather want to play or exit
System.out.println("\nChose an option \n1.Play \n2.Exit");
Scanner scan =
new Scanner(System.in);
int option =
scan.nextInt();
// if player
chose 2 program will terminat
if(option ==
2)
System.exit(0);
// generating
random number between 1 - 4580
int number =
random.nextInt(4580) + 1;
System.out.println("\nyou have to guess the word of no. : " +
number);
// asking user
to guess the word
System.out.print("Guess your word : ");
String guessWord
= scan.next();
try
{
// opening word.txt file and reaching to the
required line
File file = new File("word.txt");
Scanner scnr = new Scanner(file);
for(int i = 0 ; i < number - 1 ; i++)
{
word = scnr.nextLine();
}
// storing correct word to the variable
word
word = scnr.nextLine();
// closing file
scnr.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
// checking if
the guess word is correct or not
if(guessWord.equals(word))
System.out.println("Correct ");
else
{
System.out.println("Wrong guess, correct answer
is : " + word);
wrongCount++;
}
// if user made
10 wrong guess terminat the program as mentioned in the
question
if(wrongCount ==
10)
{
System.out.println("\nGame Over! you have made
10 wrong guesses\nBye Bye");
System.exit(0);
}
}
}
}
// for testing this code you need a word.txt file in the same directory where Hangman.java file is stored
// and word.txt file must have 4581 line of word as code is generating random number between 1 - 4081 according to question