I am not sure how to get the program to print out double letters in a word like soccer. Whenever soccer is chosen by the random generator, and I guess the letter "c" the system out prints ••c•••. I would want it to print ••cc••. Any help at all would be appreciated
import TurtleGraphics.*;
import java.util.Scanner;
import java.util.Random;
public class HangmanGame
{
public static void main(String [] args)
{
String repeat = "yes";
while((repeat.equals("yes"))||(repeat.equals ("Yes")))
{
SketchPadWindow pad = new SketchPadWindow(800, 800);
StandardPen pen = new StandardPen(pad);
Scanner scan = new Scanner(System.in);
HangmanTest hang = new HangmanTest();
Random randomGenerator = new Random();
//Ints
int index=0;
int number=0;
int counter=0;
int randomNum = 0;
//Strings
String Secretword = "";
String choose = "";
String guessLetter = "";
String guesses = "";
String diff = "";
String Pokemon [] = {"pikachu", "jigglypuff", "dugtrio", "muk", "ditto", "eevee", "mewtwo", "cyndaquil", "raikou"};
String Sports [] = {"tennis", "rowing", "golf", "lacrosse", "sailing", "soccer", "football", "baseball", "volleyball"};
String Periodic [] = {"iron", "carbon", "radon", "ununcodium", "oxygen", "magnesium", "antimoney", "iodine", "cadmium"};
String Food [] = {"pizza", "spaghetti", "muffin", "bagel", "chicken", "steak", "apple", "chips", "cookies"};
String Boardgames [] = {"life", "monopoly", "battleship", "boggle", "sorry", "operation", "blokus", "cranium", "gab"};
String Planets [] = {"mars", "pluto", "saturn", "earth", "jupiter", "uranus", "neptune", "mercury", "venus"};
String States [] = {"utah", "washington", "colorado", "california", "texas", "wyoming", "missouri", "kentucky", "connecticut"};
String Spanish [] = {"hola", "adios", "feliz", "durante", "conocer", "sobre", "decir", "trabajar", "manzana"};
String ACT [] = {"congregation", "camaraderie", "digression", "emulate", "fortuitous", "frugal", "evanescent", "hypothesis", "extenuating"};
String dashes = "";
hang.drawGallo(pen);
System.out.println("There are three difficulties to chose from with sub categories in each");
System.out.println("They are: Easy, Medium and Hard");
diff = scan.nextLine();
if(diff.equals("Easy")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Sports, Food or Boardgames");
choose = scan.nextLine();
if(choose.equals("Sports")){
randomNum = randomGenerator.nextInt(Sports.length-1);
Secretword = Sports[randomNum];
}else if (choose.equals("Food")){
randomNum = randomGenerator.nextInt(Food.length-1);
Secretword = Food[randomNum];
}else if (choose.equals("Boardgames")){
randomNum = randomGenerator.nextInt(Boardgames.length-1);
Secretword = Boardgames[randomNum];
}
}else if (diff.equals("Medium")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Pokemon, Planets or States");
choose = scan.nextLine();
if(choose.equals("Pokemon")){
randomNum = randomGenerator.nextInt(Pokemon.length-1);
Secretword = Pokemon[randomNum];
}else if(choose.equals("Planets")){
randomNum = randomGenerator.nextInt(Planets.length-1);
Secretword = Planets[randomNum];
}else if(choose.equals("States")){
randomNum = randomGenerator.nextInt(States.length-1);
Secretword = States[randomNum];
}
}else if (diff.equals ("Hard")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Periodic, Spanish or ACT");
choose = scan.nextLine();
if(choose.equals("Periodic")){
randomNum = randomGenerator.nextInt(Periodic.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("Spanish")){
randomNum = randomGenerator.nextInt(Spanish.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("ACT")){
randomNum = randomGenerator.nextInt(ACT.length-1);
Secretword = ACT[randomNum];
}
}
for(int x = 0; x< Secretword.length(); x++)
dashes += "*";
System.out.println(dashes);
while(number <= 9 && !dashes.equals(Secretword) )
{
String letter = "";
System.out.println("Please enter a letter or the entire word.");
letter = scan.nextLine();
if(letter.equals(Secretword))
{
System.out.println("You correctly guessed the word. Good job!");
break;
}
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
/*for (int x=0; x <Secretword.length() - 1; x++)
{
if (Secretword.charAt(x) == Secretword.charAt(x +1))
{
System.out.println("Word contains double");
}else
{
System.out.println("Normal word found");
}
}
*/
System.out.println("You entered a letter in the word");
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
if(number == 1)
hang.drawHead(pen);
if(number == 2)
{
hang.drawReye(pen);
hang.drawLeye(pen);
hang.drawPupils(pen);
}
if(number == 3)
{
hang.drawNose(pen);
hang.drawMouth1(pen);
}
if(number == 4)
hang.drawTeeth(pen);
if(number == 5)
hang.drawHair(pen);
if(number == 6)
hang.drawLglasses(pen);
if(number == 7)
hang.drawBody(pen);
if(number == 8)
{
hang.drawRarm(pen);
hang.drawLarm(pen);
}
if(number == 9)
{
hang.drawLleg(pen);
hang.drawRleg(pen);
}
}
if(number == 10){
System.out.println("You lose");
System.out.println("The word was:" + " " + Secretword);
}else
{
System.out.println("You win");
}
System.out.println("Game Over");
System.out.println("Would you like to play again?");
repeat = scan.nextLine();
}//end over all while loop
System.exit(0);
}//close main function
}//close class
I see you tried to fix it so you know where the problem is. The simplest way to get it working would be something like:
if(Secretword.indexOf(letter) != -1)
{
System.out.println("You entered a letter in the word");
while(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
}
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
That is until someone enters * and it'll freeze. I'll leave that to you to fix ;)
Related
I am having issues trying to make my code loop back and do the program over again until the user asks them to stop by inputting zero. I have tried a while statement but I am not sure if I implemented it correctly since all I got back was errors. I appreciate any and all the help that can be given. I have included my code below.
public class CoinTossing {
public static void main(String[] args) {
//Scanner method
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
Random rand = new Random();
// Simulate the coin tosses.
for (int count = 0; count < number; count++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
return;
}
}
}
Your main method could look something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
while (true) {
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
if (number == 0) { break; }
Random rand = new Random();
// Simulate the coin tosses.
for (int i = 0; i < number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
}
}
Here, the while loop is entered after the welcome message and will only exit the simulation when the user inputs a 0.
After the user input is retrieved, it will check if the user input 0. If the user inputs 0, it will break the while loop before the program simulates flipping the coin:
if (number == 0) { break; }
Place your code into a while loop with the exception of these two lines:
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
At the end of the Coin Toss Game the natural order of things would be to ask the User if he/she wants to play again. This allows the User to quit the application rather than being stuck in a continuous loop:
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
The whole application may look something like this:
public class CoinTossing {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
java.util.Random rand = new java.util.Random();
System.out.println("Welcome to the Coin Toss Program");
System.out.println("================================");
System.out.println();
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
}
}
I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.
public class Game {
public static void main(String[] args) {
String secretWord = "frog";
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0) {
here the loop cycles through the characters in a String, and checks if the user input guessedLetter matches a char in the string. right now the loop cycles through each char starting with the first char in the string through the last, the user must guess the letters in the exact order of they are arranged in the string, how can I fix this so that any character input matching a character in the String will be correct rather than the characters having to be in order?
for (int i = 0; i < secretWord.length(); i++) {
char guessedLetter = input.next().charAt(0);
char currentLetter = secretWord.charAt(i);
if (guessedLetter == currentLetter) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
}
else if (guessedLetter != currentLetter) {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
}
else if (correctGuesses == secretWord.length()) {
System.out.println("You Got It! The Word is: " + secretWord);
}
}
}
}
You could try it as follows:
move all the characters of secretWord to a map (key would be the character and the value would be incidences of that character in the string).
read the character from the keyboard and interate (basically, your logic).
Here is the code.
public static void main(String[] args) {
String secretWord = "frog";
Map<Character, Integer> mapOfLetters = new HashMap<>();
for (char c : secretWord.toCharArray()) {
int count = 1;
if (mapOfLetters.containsKey(c)) {
count = mapOfLetters.get(c) + 1;
}
mapOfLetters.put(c, count);
}
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0 && !mapOfLetters.isEmpty()) {
char guessedLetter = input.next().charAt(0);
if (mapOfLetters.containsKey(guessedLetter)) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
int count = mapOfLetters.get(guessedLetter) - 1;
if (count == 0) {
mapOfLetters.remove(guessedLetter);
} else {
mapOfLetters.put(guessedLetter, count);
}
} else {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
} else if(mapOfLetters.isEmpty()){
System.out.println("You Got It! The Word is: " + secretWord);
}
}
guessedLetter = input.next().charAt(0);
If you want to match the whole UserInput there should not be charAt(0).
On the other hand, if you just want to match any character, at first time you can test guessedLetter == currentLetter is true, then just exit program.
By the way, if you like, just google "KMP algorithm" to learn how to match String.
Just started a computer science degree and have been tasked with making a Hangman game, it seems to work find other than it doesn't print "You won" and I cannot see/figure out why it doesn't. Any help from you guys would be great.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
char[] alpha = new char[26];
Arrays.fill(alpha, ' ');
String a1 = "intro to programming";
String a2 = "computer";
String a3 = "mouse and keyboard";
String a4 = "skyrim";
String a5 = "hello world";
int selector = rand.nextInt(5) + 1;
char[] words = null;
char[] show = null;
if (selector == 1) {
words = a1.toCharArray();
show = a1.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 2) {
words = a2.toCharArray();
show = a2.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 3) {
words = a3.toCharArray();
show = a3.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 4) {
words = a4.toCharArray();
show = a4.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 5) {
words = a5.toCharArray();
show = a5.toCharArray();
Arrays.fill(show, '-');
}
int length = words.length;
System.out.println("Please enter the amount of tries you would like:");
int amount = scan.nextInt();
String guessed;
char guessedchar;
for (int i = 0; i < length; i++) {
if (words[i] == ' ') {
show[i] = ' ';
}
}
int x = 0;
while (amount >= 0) {
System.out.print("String to guess: ");
for (char n : show) {
System.out.print(n);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Number of tries left: " + amount);
System.out.print("Number of times you have tried: ");
for (char a : alpha) {
System.out.print(a);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Enter a guess");
guessed = scan.next();
guessedchar = guessed.charAt(0);
alpha[x] = guessedchar;
for (int i = 0; i < length; i++) {
if (guessedchar == words[i]) {
show[i] = guessedchar;
}
}
x = x + 1;
amount = amount - 1;
if (amount == 0) {
System.out.println("You lose");
return;
} else if (show == words) {
System.out.println("You won");
}
}
}
Convert the words and show arrays to Strings and check if they are equal with .equals(), this should then display the correct message
I am having trouble with my hangman programm in java class I don't seem to get the lost lives counter to work properly and also displaying the already guessed letters that are right don't display in the sequence when you make the next correct guess.
import java.util.Scanner; //imports scanner so I could use user input
import java.util.Random; // imports random picker for words, to pick a random word
public class javaxx {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
StringBuffer buffer = new StringBuffer();
String wordToGuess;
int wordLength;
int wordToGuessLength;
int position;
int livesLost = 0;
int totalLives = 7;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//declare variable
//String wordToGuess[] = new String[29];
//insert array for words and their values
String[] myStringArray = new String[]{"programming","exhaustive","violin","selection","repetition","serendipity","watermelon","football","mobilephone","handbag","teddybear","cardigan","waterfall","cupcake","pineapple","strawberry","collection","chicken","tablecloth","candlestick","notebook","radiator","champagne","wineyard","parent","circus","snowbell","clocktower","mermaid","cardigan"};
//Display the rules of the game
System.out.println("You are playing the game Hang Man. You have to guess the letters in the word. You will see how many letters are in the word and you have 7 changes to be wrong. ");
//choose a random word from the array
wordToGuess = myStringArray[(int) (Math.random() * myStringArray.length)];
//determine the length of the word
wordLength = wordToGuess.length();
//show the player how many letters are in the word
System.out.println("The word you are quessing has " + wordLength + " letters in it");
lettersRemaining = wordLength;
for (position = 0; position < wordLength; position++) {
sb.append("_ ");
}
System.out.println(sb.toString());
//loop starts
while (lettersRemaining > 0 && livesLost < 7) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (wordToGuess.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < wordLength; position++) {
if (wordToGuess.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("_ ");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(wordToGuess);
}
}
}
change this line
System.out.print(totalLives -= livesLost);
to
System.out.print(totalLives - livesLost);
this was the problem with liveslost counter.