Resetting a variable to new value in loop - java

I have a small hang man type game in which the user guesses a letter and tries to determine one of the random words from a string array. The issue is that once the user wants to play again with a new random word, the old word still shows up along side with it ?
import java.util.Random;
import java.util.Scanner;
import java.lang.Character;
public class Game
{
public static void main(String[] args)
{
String[] words = {"Computer", "Software" , "Program" ,
"Algorithms", "Unix" , "Mathematics" ,
"Quick" , "Bubble" , "Graph" };
Random rnd = new Random();
Scanner sc = new Scanner(System.in);
int index;
String word = "",
invisibleWord = "",
newString = "",
guess,
status;
while(true)
{
index = rnd.nextInt(words.length);
word = words[index];
for(int i = 0; i < word.length(); ++i)
invisibleWord += "*";
while(true){
System.out.print("(Guess) Enter a letter in word "
+ invisibleWord + " > ");
guess = sc.nextLine();
for(int j = 0; j < word.length(); ++j)
if(guess.toUpperCase().equals(Character.toString(word.charAt(j)).toUpperCase())){
if(j == 0){
newString = invisibleWord.substring(0,j) + guess.toUpperCase() + invisibleWord.substring(j + 1);
invisibleWord = newString;
} else {
newString = invisibleWord.substring(0,j) + guess + invisibleWord.substring(j + 1);
invisibleWord = newString;
}
}
if(invisibleWord.contains("*")) continue;
else break;
}
System.out.println("The word is " + word);
System.out.print("Do you want to guess another word ? " +
"Enter y or n > ");
status = sc.nextLine();
if(status.toUpperCase().equals("Y")) continue;
else if(status.toUpperCase().equals("N")) break;
}
}
}
SAMPLE RUN:
(Guess) Enter a letter in word ****** > a
(Guess) Enter a letter in word ****** > e
(Guess) Enter a letter in word *****e > i
(Guess) Enter a letter in word *****e > o
(Guess) Enter a letter in word *****e > u
(Guess) Enter a letter in word *u***e > b
(Guess) Enter a letter in word Bubb*e > l
The word is Bubble
Do you want to guess another word ? Enter y or n > y
(Guess) Enter a letter in word Bubble******** >
The problem occurs in the last line, why is Bubble still showing up as a word when it is supposed to be reset to a new random word ?

your question itself answers it! you need to reset the variable. try following
if(status.toUpperCase().equals("Y"))
{
invisibleWord = "";
continue;
}

You are not resetting invisibleWord after each iteration.
while(true)
{
invisibleWord="";
index = rnd.nextInt(words.length);
word = words[index];
for(int i = 0; i < word.length(); ++i)
invisibleWord += "*";
while(true){
System.out.print("(Guess) Enter a letter in word "
+ invisibleWord + " > ");
guess = sc.nextLine();
for(int j = 0; j < word.length(); ++j)
if(guess.toUpperCase().equals(Character.toString(word.charAt(j)).toUpperCase())){
if(j == 0){
newString = invisibleWord.substring(0,j) + guess.toUpperCase() + invisibleWord.substring(j + 1);
invisibleWord = newString;
} else {
newString = invisibleWord.substring(0,j) + guess + invisibleWord.substring(j + 1);
invisibleWord = newString;
}
}
if(invisibleWord.contains("*")) continue;
else break;
}
System.out.println("The word is " + word);
System.out.print("Do you want to guess another word ? " +
"Enter y or n > ");
status = sc.nextLine();
if(status.toUpperCase().equals("Y")) continue;
else if(status.toUpperCase().equals("N")) break;
}
}
}

Related

Hangman game: How to find the word?

I have to create a hangman game. I am stuck in the last step. In fact, when the user finds the word my input asks yet a letter.
Here an example: (the word to find is "non")
Enter your letter please : n
n _ n
Enter your letter please : o
n o n
Enter your letter please :
n o n
My problem is probably my wordFind, I don't understand how to manipulate this ?
String[] words = {"yess", "non"};
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean [wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
while(numberAttempt > 0 && !wordFind){
System.out.println("Number of attempt(s) " + numberAttempt);
for(int i=0; i < wordRandom.length(); i++){
if(letterGuess[i]){
System.out.print(wordRandom.charAt(i));
}
else{
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for(int i=0; i < wordRandom.length(); i++){
if(wordRandom.charAt(i) == letter){
if(letterGuess[i]){
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
}
}
if(alreadyFound){
System.out.println("Letter already proposed and it has been found ! ");
} else{
if(letterFound == 1){
System.out.println("The letter is correct ! ");
}
else if(letterFound > 0){
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else{
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}
You need to add a solved condition like this
boolean wordFind = false;
int numberAttempt = 5;
boolean solved = false;
while(numberAttempt > 0 && !wordFind && !solved){
after you update letterFound, set solved
letterFound++;
if (letterfound == wordRandom.length()) {
solved = true
}
Then at the end after the while loop, if solved is true, congratulate the user.
You can create a variable int amountCorrect = 0; and use that as a check. Every time the user gets a right letter, add to amountCorrect the number of letters there are. At the beginning of the while loop, create a boolean check that checks if the amountCorrect variable is the same as the length of the wordRandom. I know your code is kind of long, so I put a comment next to the lines where I added code:
String[] words = { "yess", "non" };
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean[wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
int amountCorrect = 0; // The amountCorrect variable
while (numberAttempt > 0 && !wordFind) {
System.out.println("Number of attempt(s) " + numberAttempt);
// This is the boolean check
if (amountCorrect == wordRandom.length()) {
System.out.println("You Win!");
break;
}
for (int i = 0; i < wordRandom.length(); i++) {
if (letterGuess[i]) {
System.out.print(wordRandom.charAt(i));
} else {
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for (int i = 0; i < wordRandom.length(); i++) {
if (wordRandom.charAt(i) == letter) {
if (letterGuess[i]) {
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
// add to amountCorrect
amountCorrect++;
}
}
if (alreadyFound) {
System.out.println("Letter already proposed and it has been found ! ");
} else {
if (letterFound == 1) {
System.out.println("The letter is correct ! ");
}
else if (letterFound > 0) {
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else {
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}

Strings B word assignment

I have to write a program where a user to enter 5 words, these words must be stored into a string array. When the user is finished, you must display the number of times a word beginning with the letter ‘B’ was entered, lower or uppercase, and also re-state the B words. I can't get it to tell me how many 'B' words there is and what they are.I use java, ready to program since I'm a student, I don't use scanner and all that
//Asking user to input 5 words
System.out.println ("Please enter 5 words");
System.out.println ("====================");
//set up loop so that x is the index variable going from 0 to 4
//fill words array with five words
int fromIndex = 0;
int counter = 0;
for (int x = 0 ; x <= 4 ; x = x + 1)
{
System.out.print (" ");
words [x] = keyboardInput.readLine ();
//change word to lowercase
String lower = words[x].toLowerCase();
while(fromIndex !=-1)
{
fromIndex = lower.indexOf("b",fromIndex);
if (fromIndex !=-1)
{
//character was matched
counter = counter + 1;
fromIndex++;
}
}
}
System.out.print ("You entered " + counter + " 'B' words and they were: ");
This is what I get:
Please enter 5 words
Food
Billy
Sill
Bear
Pop
You entered 0 'B' words and they were:
You never reset your fromIndex, and you don't need a fromIndex or a while loop like that. I would use String.startsWith(String). Like,
for (int x = 0; x < 5; x++) {
System.out.print(" ");
words[x] = keyboardInput.readLine();
if (words[x].toLowerCase().startsWith("b")) {
counter++;
}
}
Alternatively,
if (Character.toLowerCase(words[x].charAt(0)) == 'b') {
counter++;
}
You can Use indexOf function on your String. If that is 0 it means your word Starts with b.
for (int x = 0 ; x <= 4 ; x = x + 1)
{
System.out.print (" ");
words [x] = keyboardInput.readLine ();
//change word to lowercase
String lower = words[x].toLowerCase();
if(lower.indexOf("b") == 0){
counter++;
}
}
System.out.print ("You entered " + counter + " 'B' words and they were: ");
Here is the complete version:
public class Bwords {
public static void main(String [] args){
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.println ("Please enter 5 words");
System.out.println ("====================");
String[] words = new String[5];
int count=0;
String [] b_words=new String[5];
for (int x = 0; x <= 4; x++) {
System.out.print(x+1+" word: ");
words[x] = input.next();
if (words[x].toLowerCase().startsWith("b")) {
count++;
b_words[x]=words[x];
}
}
System.out.print ("You entered " + count + " 'B' words and they were: ");
for (String b_word : b_words) {
if (b_word != null)
System.out.print(b_word + " ");
}
}
}
Output
Please enter 5 words
1 word: Food
2 word: Billy
3 word: Sill
4 word: Bear
5 word: Pop
You entered 2 'B' words and they were: Billy Bear

Hangman stats error

My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}

Hangman While loop solution

import java.util.*;
public class Hangman
{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter word: ");
String Word = kybd.nextLine();
String dashWord = Word.replaceAll(".", "-");
System.out.println(dashWord);
StringBuilder dashWordB = new StringBuilder(dashWord);
System.out.println("Please guess a letter: ");
char letterGuess = kybd.next().charAt(0);
int lettersGuessed = 0;
// While loop should exit once letterGuessed is equal to Word.length()
while (lettersGuessed <= Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == Word.length() - 1)
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
}
}
System.out.println(dashWordB);
System.out.println(lettersGuessed);
}
}
Having trouble exiting while loop when all letters of dashWordB are guessed correctly. Any help greatly appreciated.
Just add the following in your while loop:
if(lettersGuessed == Word.length()){
break;
}
That should help you fix the problem.
Also as suggested by the others change the while condition to the following:
while (lettersGuessed < Word.length())
So your while loop should be the following:
while (lettersGuessed < Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == (Word.length() - 1))
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
if(lettersGuessed == Word.length()){
break;
}
}
}
Your problem is here: while (lettersGuessed <= Word.length()){
You will exit only if lettersGuessed > Word.length() or if you guessed correctly a letter more than the length of the word.
Try while (lettersGuessed < Word.length()){

why is indexof not working?

I have a program for a hangman game and the indexof is not working for me? its on line 30. I have been trying to figure it out but I cannot.if (guessedWord.indexOf(letter) >= 0). I will keep trying to find out what I did wrong
import java.io.PrintStream;
import java.util.Scanner;
public class Hangman
{
public static void main(String[] args)
{
String[] words = { "write", "program", "that", "receive", "positive" };
Scanner input = new Scanner(System.in);
char anotherGame;
do
{
int index = (int)(Math.random() * words.length);
String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;
while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);
if (guessedWord.indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}
System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses + (numberOfMisses <= 1 ? " time" : " times"));
System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}
You are passing in a char where String is expected. Try using String.valueOf(letter) like this:
if (guessedWord.indexOf(String.valueOf(letter)) >= 0) {
// Your code
}
StringBuilder#indexOf(char) is undefined. You could do
if (guessedWord.indexOf(Character.toString(letter)) >= 0) {
there's no indexOf(char) method for a StringBuilder.
guessedWord.indexOf(letter)
should be
if (guessedWord.toString().indexOf(letter) >= 0) {

Categories