Submitted by: Submitted by Spiderman41987
Views: 115
Words: 353
Pages: 2
Category: Other Topics
Date Submitted: 06/15/2014 11:56 AM
import java.util.Random;
import java.util.Scanner;
// Class name and file name must match!
public class Hangman
{
// We have to have a main!
public static void main(String[] args)
{
//creates while statement to restart game if wanted
while (true)
{
//create scanner
Scanner userInput = new Scanner(System.in);
//create array words
String[] words = { "football", "soccer", "nissan", "computer", "television", "london", "sneakers"};
Random r = new Random();
//create variable attempts
int attempts = 20;
//creates string secret word containing random object from words array
String secretWord = words[r.nextInt(words.length)];
//Store the length which will be used to see if puzzle was solved.
int length = secretWord.length();
//Store a temp array which will be displayed to the user
char[] temp = new char[length];
//initialize the array.
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Enter a letter in a word: ");
while (attempts 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
// makes sure user enter one character
String test = userInput.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
//Find matches
int foundPos = -2;
int foundCount = 0;
while((foundPos = secretWord.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
length--;
}
// prints if guess was in the secret word or not
if(foundCount == 0)
{
System.out.println("Sorry, " + test + " is not in the word");
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}...