How to break from a loop after finding a word - java

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.

Related

Resetting Counter Java

import java.util.Scanner;
public class VowelsAndConsonants {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int ConsonantCount = 0;
int VowelCount = 0;
int num = 0;
int x = 0;
while(true) {
System.out.print("Enter a string: ");
String userInput = input.next();
num = userInput.length();
for(x = 0; x < num ; x++) {
char c = userInput.charAt(x);
if (Character.isLetter(c)){
c = Character.toUpperCase(c);
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
VowelCount++;
else
ConsonantCount++;
}
}
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
System.out.println("Do you want to enter another string? ");
String loopAgain = input.next();
if (loopAgain.equalsIgnoreCase("N")) {
break;
}
}
}
}
How do I reset the VowelCount and ConsonantCount after looping again? Currently, it's adding onto the counter without resetting to zero. Please help. My instructor wants me to break out of the loop if I say N or loop again if its any other character
I'm assuming you want to reset it after you print?
All you need to do is assign it like any other variable
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
ConsonantCount = 0;
VowelCount = 0;
Another route you could take would be to declare your variables at the beginning of the while loop. This way, every time the while loop runs, it re-initializes the variables to zero, so you don't have to even reset it.
while (true) {
int ConsonantCount = 0;
int VowelCount = 0;
....
}

print"we don't found this letter" java with loop

this my program
import java.util.*;
public class LeTter { //open class name
static Scanner keyboard = new Scanner(System.in); // Scanner
public static void main(String[] args) { //open main class
char letter; //decl
int y, x, z; //decl
boolean check = false;
System.out.println("Enter 8 letters: "); // print sentince
char[] des = new char[8]; //array
for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
des[y] = keyboard.next().charAt(0); //initialize
} // close for loop
System.out.println("Enter any letter to check about it: "); //will apper to the user
letter = keyboard.next().charAt(0); //initi
for (x = 0; x < des.length; x++) { //for loop opens
if (des[x] == letter) { //open if loop
System.out.println("we found it's " + des[x] + " and the index of it is " + x);
System.out.println("so we will show you this letters " + x + " times");
for (z = 0; z < x; z++)
System.out.println(des[x] + " ");
check = false;
} //close if loop
if (true)
System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
} // close for loop
} //close main
} //close class
put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it
example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it << how can I do this??
another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it << i did this , i want the first one ""onlly""
I skip the input and begin from the loop of your code, change it to:
for (x = 0; x < des.length; x++)
{ // for loop opens
if (des[x] == letter)
{ // open if loop
check = true;
System.out.println("we found it's " + des[x] + " and the index of it is " + x);
break; // you want to show 1st one only, right?
} // close if loop
} // close for loop
if (!check)
System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
I've shortened your code, as you can just add the user's input into a char array, and remove the spaces.
I used break; to get out of the loop once the first char was found, you can remove this if you want to mind multiple instance of it.
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter 8 letters: ");
String letters = keyboard.nextLine().replaceAll(" ", "");
char cArray[] = letters.toCharArray();
System.out.println("Enter any letter to check about it: ");
char letter = keyboard.next().charAt(0);
boolean found = false;
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == letter) {
System.out.println("We found " + letter + " at position " + i);
found = true;
break; //used as you specify only to find the first one
}
}
if (!found) {
System.out.println("Are you sure about the letter you entered? We didn't find it");
}
}
Try it online!

Creating simple hangman program in java, trouble with for loop

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.

java source code hangman

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.

How do I make a String unusable the second time in a loop?

I'm new to this site. I've decided to create a console base hangmaan game and I've been doing ok up till now. My current problem has me stuck.
I'm trying to make it so that if the user has input a letter and it has been marked as correct or incorrect. The program should then not let the user input that same letter again in later iterations of the while loop.
The comments should give you a better idea of what I'm talking about.
Can anyone please help me?
package hangMan2;
import java.io.IOException;
import java.util.Scanner;
public class mainClss {
public static void main(String[] args) {
int point = 0;
int numberOfLetterInWord;
// prompt user for input and store input into String word
System.out.println("Enter a word in lower case from the dictionary: ");
Scanner inputWord = new Scanner(System.in);
String word = inputWord.next();
// letters remaining in word equals the length of the word at the start
int lettersRemainingInWord = word.length();
for (int i = 0; i < 30; i++) {
System.out.println("\b");
}
// while points are above 7 (7 is when man is hung) and there's more
// than one letter remaining do all the following:
while (point > -7 && lettersRemainingInWord >= 1) {
//prompts user to input letter guess and stores in letter
System.out.print("\nEnter a letter for this " + word.length()
+ " letter word: ");
Scanner inputLetter = new Scanner(System.in);
String letter = inputLetter.next();
if (word.contains(letter)) {
System.out.println("Correct!");
point += 1;
System.out.println("Score: " + point);
lettersRemainingInWord -= 1;
//I need code here to remove the current letter from being able to be used again
if (lettersRemainingInWord > 0) {
continue;
}
else {
System.out.println("\nYou win!!!");
System.out.println("The word was: " + word);
break;
}
}
else {
System.out.println("Incorrect\n");
point -= 1;
System.out.println("Score: " + point);
//I need code here to remove the current letter from being able to be used again
if (lettersRemainingInWord > 0) {
continue;
}
else {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
break;
}
}
}
if (point <= -7) {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
}
}
}
You could test whether the letter is in a Set. If not, accept it and add it to the set. If so, then reject it.
Set<String> usedLetters = new HashSet<String>();
boolean isUsedLetter(String letter) {
if (usedLetters.contains(letter)) {
return true;
} else {
usedLetters.add(letter);
return false;
}
}
You can use an ArrayList to hold the characters that have already been typed and then check the list to see if the character is in there.
List<Character> used = new ArrayList<Character>();
char let = //letter that they inputted
if(used.contains(let)) {
//do something
}
else {
used.add(let);
}

Categories

Resources