Making a hangman game [duplicate] - java

This question already has answers here:
Creating hangman game without arrays [closed]
(3 answers)
Closed 9 years ago.
Logic:
This is how the output should look like. http://prntscr.com/1is9ht i need to find the index of guess in the orginalString. If that's true then it should replace the question mark at the index with the character read in the string guess. After that it should take out that char from the string "abcdefghijklmnopqrstuvwxyz".
If originalString doesn't contain guess than it should only take out that char from the string "abcdefghijklmnopqrstuvwxyz" I looked up this question on google and found a bunch of codes, they were all using arrays or something that I have not learned in the classes. So please don't use arrays. I am stuck at the if else statement. Is there any way to solve this problem without using Arrays.
int count=1;
while (count<=24){
Scanner keyboard = new Scanner(System.in);
int length;
String originalString;
String guess;
String option= "abcdefghijklmnopqrstuvwxyz";
String questionmarks;
System.out.println("Please enter a string");
originalString=keyboard.nextLine();
length=originalString.length();
questionmarks = originalString.replaceAll(".", "?");
System.out.println("Original String: "+originalString);
System.out.println("Guessed String: "+questionmarks);
System.out.println("Characters to choose from: "+option);
System.out.println("Please guess a character");
guess=keyboard.nextLine();
if (originalString.contains(guess)){
count++;
}
else{
option.replace(guess, "_");
count++;
System.out.println(option);
}
Please suggest me some code that doesn't implement array concept for my problem,
Any help will be appreciated

A few things that I noticed from a cursory glance:
.replace() returns a String, it will not modify option unless you do:
option = option.replace(guess, "_");
Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder to have a String that's initialized to all -. Then when someone guess a correct letter, you can replace the - with the guess.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess, if you've determined that the character at position i should be replaced by guess, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}

Related

How do you, using a set of random given letters, check if a word is created with only those given letters

In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}
else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.
You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

How to prompt a user for additional input for a Java Hangman game?

I have an assignment for a beginner Java course that has asked me to create a class called Hangman. The program is supposed to prompt a user (player one) to input a String, then print dashes on the screen for each character in the screen. The program then asks a second user (player two) to take guesses one character at a time until either the word has been guessed, or they have six failed attempts. As each correct guess is verified, the corresponding dash in the string is replaced with the correct letter.
At this point I have created code that will scan in a user String, and replace the String with dashes. The code also prompts the second user for a comparison letter. The code will also replace the first correct guess in the dash String.
The problem I have at this point is that I can't seem to find a way to prompt the user for additional input after the first guess. The program will accept the first correct guess, replace it, and then terminate. I removed a portion of code that checked how many incorrect / correct guesses had been input, because at this point the code would run through constantly incrementing the count and terminate the program. Any help with this problem would be greatly appreciated.
Update:
I have reworked my code to remove unwanted / unnecessary branches. Here is my updated code. At this point, I am receiving too many incorrect guesses. The code is counting every iteration through the array that does not match as incorrect. I appreciate any help you can offer.
public class Hangman
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
String word;
String letter = "";
boolean gameOver = false;
int correct = 0;
int incorrect = 0;
int index = 0;
Scanner userIn = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = userIn.nextLine();
String[] wordArray = word.split("");
int wordLength = word.length();
String[] wrong = {};
String[] right = {};
String[] dashes = new String[wordLength];
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
for(int i = 0; i < wordLength; i++)
{
dashes[i] = "-";
}
for(int i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
System.out.println();
while(incorrect < 6)
{
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
letter = letter.toLowerCase();
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
}
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
dashes[i] = letter;
System.out.println("Correct!");
for( i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
correct++;
}
else
{
incorrect++;
}
}
}
if(correct == wordLength)
{
System.out.println();
System.out.println("You Win!!");
System.out.println();
}
if(incorrect == 6)
{
System.out.println("You Lose.");
System.out.println("The word was " +word);
System.out.println();
}
}
}
So, that's a hefty amount of code. And I see some interesting decisions all over the place. So since you're learning I'll help you help yourself.
Before taking on an application like this you should think about your logic first (psuedo-code) before actually coding. So for a hangman game you probably want something like:
player 1 enters phrase
while wrong_guesses < max_incorrect:
prompt player 2 for a letter
check the phrase for that letter
if found
replace dashes with the letter
else
wrong_guesses++
print status message
Just glancing at your code I can see multiple places where you're asking for new input. This means you are not effectively using your loops. Your application has a lot of unnecessary branches and cleaning it up will help you debug. As an exercise, you can walk through your code and write its' psuedo-code, then compare it to mine.
Good luck!
Update:
With respect to the new and much improved code, your check loop is wrong. It should look more like this:
boolean found = false;
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
found = true;
// replace dashes, and you don't need to loop here,
// do it after the check for better efficiency
}
}
//Outside of the loop
if (!found)
{
incorrect++;
}
//Print the current status here then
Also, your check for only 1 letter can be subverted (enter aa, then aa again). That block should be:
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
//letter = userIn.nextLine();
continue; //This tells java to restart the loop
}

Using methods to check for palindromes

I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

Categories