Java homework hangman [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So for a class we are having to make a hangman game that can take a user input for a word and then have another person solve for it. It has to be able to recognize multiple repeating letters in the word or I would be done. Below is my code, it works great until I remove the break statement in my checkformatch method so that it goes past the initial finding of a letter. With the break in there it never finds the second third etc repeated letters, without it, it returns that each letter that is not the letter searched is a miss and reduces my life count. What I'm needing is some hints on how to search my array for the letter that is inputted as a guess and return their index positions in the array without it thinking each character in the array that is not the one guessed is a wrong input. Thank you in advance.
package hangman;
import java.util.Scanner;
class Game {
int livesRemaining;
String letterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord ;
Scanner input = new Scanner(System.in);
boolean isFound;
int a;
public Game()
{
this.setLives(8);
//this.output();
System.out.println("Player 1 please enter the word to be searched: ");
wordInput = input.nextLine();
aOfWord = wordInput.toCharArray();
hiddenWord = new char[aOfWord.length];
for(int j = 0; j < hiddenWord.length; j++)
hiddenWord[j] = '*';
this.output();
while(livesRemaining > 0)
{
System.out.println("Please choose a letter: ");
letterGuessed = input.nextLine();
this.checkForMatch(letterGuessed);
if(isFound == true)
{
hiddenWord[a] = letterGuessed.charAt(0);
}
else
{
System.out.println("Is not found!");
this.reduceLives();
}
this.output();
}
}
public void setLives(int a)
{
this.livesRemaining = a;
}
public void reduceLives()
{
livesRemaining = livesRemaining -1;
System.out.println("Lives remaining: " + this.getLives());
}
public int getLives()
{
return livesRemaining;
}
public void output()
{
System.out.println("Lives remaining: " + this.getLives());
System.out.println("Word found so far ");
for(int i = 0; i < hiddenWord.length; i++)
{
System.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i = 0; i < aOfWord.length; i++)
{
//System.out.println("Comparing " + l.charAt(0) + " To " + aOfWord[i]);
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}

To start with, if you want to return the indices of the chars, you'll need to add them somewhere, I would recommend returning an ArrayList which would hold all of your values. This is because an ArrayList can grow in size if it is too small and you'll not really need to worry about an out of bounds issue.
Your current form of checkForMatch works for what you want, but consider returning a boolean instead of setting your isFound field to true/false. Also there is a contains method that the String class has which you can call, so an alternative to your checkForMatch would be possible sort of like
String yourString = "Hello";
String yourChar = "e";
System.out.println(yourString.contains(yourChar));
Which of course would print true!
Now, to get the indices, you already traverse the array and compare characters in your checkForMatch() method, why not simply create an ArrayList<Integer> matchedIndices = new ArrayList<Integer>(); at the top of your method, and instead of setting isFound to true, call matchedIndices.add(i); if the characters match, and then at the end return the ArrayList?
You would of course have to swap your return type from void to ArrayList, but there are many ways to go about this, this being just the first that came to my head!

Your algorithm seems fine. However, it will only get you the last matching character because a will be rewritten whenever he finds a matching character.
I think a really simple solution would be to do this in your checkForMatch method:
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
hiddenWord[i] = l.charAt(0);
}
and also this in your game method...
if(!isFound)
{
System.out.println("Is not found!");
this.reduceLives();
}
You don't have to use this. by the way. That is only necessary in certain cases. Take a look at this.

Related

Writing a program that takes input from a user as an array and compares it to another array to check for correct answers using a while loop

this is probably a really newbie issue, but I can't quite find an answer that was answered without using a for loop. I have one array set as a constant which contains the correct answers to the test. The program takes in user input and then compares it to the constant array and counts the amount of correct answers. I should not have to import any libraries and should complete the method with a while loop.
I want to iterate through the users input through the ANSWER constant and create a count for all of the correct answers.
Here is a snippet of my class (I've excluded the method that prompts the user for answers to keep things simple).\
public class DriverExam{
public static final char[] ANSWER = {'B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
private char[] driversAnswers;
InputReader reader;
public DriverExam(){
reader = new InputReader();
driversAnswers = new char[20];
}
public int getTotalCorrectAnswers(){
int correct = 0;
int index = 0;
while (index < ANSWER.length){
index++;
if(driversAnswers.equals(ANSWER)){
correct++;
}
System.out.println(index);
System.out.println(correct);
}
return correct;
The issue is most likely to do with the if statement but I can't seem to find a way to iterate through an arrays indices and compare them to another array.
EDIT: My current method looks like this:
public int getTotalCorrectAnswers(){
int correctAnswer = 0;
int index = 0;
while(index < ANSWER.length){
if(ANSWER[index]==driversAnswers[index]){
correctAnswer++;
index++;
}
// System.out.println(index);
System.out.println(correctAnswer);
}
return correctAnswer;
For a couple of attempts I was getting some actual counts happening but it appeared that it would stop the counter once it encountered a different value. But as things stand now I am stuck with a result value of 0's
as already described in the comments, you cannot compare arrays like this. driverAnswers.equals(ANSWER) only compares the references, in this case it will return a false, because the references are different. If you want to check an array for equality you can use Arrays.equals(arr1, arr2). In this case the equals method is called on every element in the array. If the objects in the arrays override this method correctly, this method will return the desired result.
However, you did mention not to use other libraries.
The simplest solution would then be to iterate through each element and check for equality
EDIT: because you don't need the else case i made a little editing here
while(index < ANSWER.length){
if(driverAnswer[index] == ANSWER[index])
correct++
index++
}
first you to check the size of the both array must equal, if it so then you can directly use Arrays.equals method for all correct answer else you can loop through the right answer, look out the simple iteration below
int correctAnswer = 0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
for (int i=0;i<ANSWER.length;i++) {
if(ANSWER[i]==driversAnswers[i])
correctAnswer++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
You can use while loop there instead of for
int correctAnswer = 0,index=0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
while (index<ANSWER.length) {
if(ANSWER[index]==driversAnswers[index])
correctAnswer++;
index++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
USE THIS FOR YOUR REFERENCE
import java.util.Arrays;
class Test{
public static void main(String[] args) {
char[] ANSWER = {'B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
char[] driversAnswers = {'x','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
int correctAnswer = 0,index=0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
while (index<ANSWER.length) {
if(ANSWER[index]==driversAnswers[index])
correctAnswer++;
index++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
}
}

I'm trying to make a hangman game, but I'm getting hung up on things like arrays [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();

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()));
}
}

Making a hangman game [duplicate]

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);
}
}
}

I fixed my dilemma with the looping issue. But How can I make it so I dont have to press R? As in, any other key pressed will loop? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
import java.util.Scanner;
public class CurrencyConversion{
public static void main(String[] args){
// declare and initialize variables
double dollars = 0;
//double euro = 0;
// declare scanner
Scanner scan = new Scanner(System.in);
int loopVal = 0;
boolean loop = true;
while( loopVal < 1 && loop == true){
//Prompt user for dollar amount
System.out.print("Enter the dollar amount $");
dollars = scan.nextDouble();
loopVal ++;
loop = false;
while( loopVal == 1 && loop == false){
System.out.print("Press Q to quit,or R to resume");
String input = scan.nextLine();
if( input.equalsIgnoreCase("Q")){
break;
} // end if one
if (input.equalsIgnoreCase("R"))
{
loop = true;
loopVal = 0;
}// end else
} // end second while
} // end first while
}// end main method
}// end class
First, your code is case sensitive - "Q" would work but 'q' would not. You should use input.equalsIgnoreCase("Q") to avoid this.
Second, you're not doing anything when "input == Q" - perhaps you want to simply use break to escape your while loop in that case? Be careful without {}'s around your if...only the first line after the if is executed if you don't wrap that in {}'s.
I think you want something like this:
while( loopVal == 1 && loop == false){
System.out.print("Press Q to quit, any other key to resume ");
String input = scan.nextLine();
if ( input.equalsIgnoreCase("Q"))
{
loop = false;
}
else {
// whatever else
}
}
Java doesn't understand input != "Q" , remember that String is a class in Java.
rather - use public boolean equalsIgnoreCase or similar.
See this - http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals%28java.lang.Object%29
Also here, Compare strings example - http://www.roseindia.net/java/beginners/CompString.shtml

Categories