3.10 Lab
You will create a two-player version of the Hangman game. The program should first ask for the first player to enter a word and save the word. Next, the second player should be allowed to guess letters. If a letter appears in the word, then they should be told at what position. After 6 guesses, the player has one shot of guessing the word. A possible run of the program follows (user input is in italic).
Player 1 enter word: mississippi
Player 2 enter guess: c
No letter c
Player 2 enter guess: d
no letter d
Player 2 enter guess: e
no letter e
Player 2 enter guess: m
at position: 1
Player 2 enter guess: a
no letter a
Player 2 enter guess: i
at position 2 5 8 11
Enter word: mississippi
This is correct!
Use a for loop to iterate through all the guesses. Use a nested for loop to iterate through
all the characters of the word. When there is a hit (i.e., the user character matches a word
character), report the value of the index of the character in the word. Do not forget to add
one to the result because the characters of a string are counted starting at index 0.
This was pretty easy. I added a small feature above what the exercise asked for which was to convert all inputs to lower case so that there wouldn't be a false negative due to capitalization.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
String word, output;// user input, word to guess, program output
char guess;// letter guessed
Scanner keyboard = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = keyboard.next().toLowerCase();// convert input to lower case
int length = word.length();// get length of word
for (int x = 0; x < 6; x++) {// loop for 6 guesses
System.out.print("Player 2 guess a letter: ");
guess = keyboard.next().toLowerCase().charAt(0);// take first character and make it lower case
output = "at position ";
for (int i = 0; i < (length); i++) {// loop through all characters in the word
if (guess == word.charAt(i))// check if corresponding characters match
output = output + (i + 1) + " ";// add to response line
}
if (output.equals("at position "))// if no matches found
output = "No letter " + guess;
System.out.println(output);
}
System.out.print("Player 2 guess the word: ");// prompt user
if (keyboard.next().toLowerCase().equals(word))// if input converted to lower case equals the word
System.out.println("You won!");
else
System.out.println("Sorry, that is incorrect.");
keyboard.close();
}
}

No comments:
Post a Comment