You are on page 1of 3

import java.util.

*;
public class MoreStringPractice
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a full name: ");
String full = keyboard.nextLine();
full = full.trim(); // get rid of leading/trailing spaces
String first = "";
String last = "";
int commaPosition = full.indexOf(",");
int space = full.indexOf(" ");

//

if (commaPosition == -1) // no comma, so first_last


{
int space = full.indexOf(" ");
first = full.substring(0, space);
last = full.substring(space + 1);
}
else
{
last = full.substring(0, commaPosition);
first = full.substring(space + 1);
}
System.out.println("First name: " + first);
System.out.println("Last name: " + last);
// Implement a very simple version of Hangman
String secretWord = "";
// Choose a random word
Random r = new Random();
int choice = r.nextInt(4);
if (choice == 0)
{
secretWord
}
else if (choice ==
{
secretWord
}
else if (choice ==
{
secretWord
}
else if (choice ==
{
secretWord
}

= "computer";
1)
= "purple";
2)
= "algorithm";
3)
= "heuristic";

String usedLetters = "";


String userWord = "";

// Use a loop to create displayed word for user


for (int i = 0; i < secretWord.length(); i = i + 1)
{
userWord = userWord + "*";
}
int errors = 0;
while (!userWord.equals(secretWord) && errors < 6)
{
System.out.println("Current status: " + userWord);
System.out.println("You have " + (6 - errors) + " guess(
es) left.");
System.out.println("Letters used: " + usedLetters);
System.out.println();
System.out.print("Enter character guess: ");
String guessAsString = (keyboard.nextLine()).trim().toLo
werCase();
char nextGuess = guessAsString.charAt(0); // get first c
haracter
if (usedLetters.indexOf(nextGuess) > -1)
{
// print error message
System.out.println("You already used that letter
!");
errors = errors + 1;
}
else
{
usedLetters = usedLetters + nextGuess;
// Reveal any occurrences of nextGuess in secret
Word
String result = "";
for (int i = 0; i < secretWord.length(); i = i +
1)
{
if (secretWord.charAt(i) == nextGuess) /
/ matched the letter
{
result = result + nextGuess; //
show guessed letter
}
else
{
result = result + userWord.charA
t(i); // replace with existing character
}
}
if (result.equals(userWord)) // no changes
{
System.out.println("Incorrect guess");
errors = errors + 1;
}
else

{
System.out.println("Good guess!");
}
userWord = result;
}
}
if (errors > 5) // lost the game
{
System.out.println("YOU LOSE!");
}
else
{
System.out.println("Congratulations. You won... this tim
e.");
}
}
}

You might also like