This is for a Hangman game. I am using a SortedSet to store the guesses that the user inputs. These letters are stored as char. What I am trying to do is compare each character in a given word to every character in the SortedSet, and append a matched character to a returned String. If it doesn't match, a '-' is appended instead.
For example:
I have a set that contains the guesses: 'a', 'e', 't'
I have a word: apple
The method should return the string "a---e"
Right now, I have a method that generates a String that fits the format I need for one character. I am not sure how to modify it so it works for all characters in a collection.
I don't want to run the entire if/else structure for all of the characters in the collection as that would add too many dashes, so I don't think I can use a for-each loop.
private int generatePattern(String s, char guess) {
String pattern = "";
for (int i = 0; i < length; i++){
if (s.charAt(i) == guess){
pattern += guess + " ";
} else {
pattern += "- ";
}
}
return pattern;
}
Well to start with it sounds like you should change your method's return type and parameters - you want a set of letters, after all. And sets have a contains
method. So I think you want something like:
public static String hideNonGuesses(String input, Set<Character> guesses) {
char[] result = input.toCharArray();
for (int i = 0; i < result.length; i++) {
if (!guesses.contains(result[i])) {
result[i] = '-';
}
}
return new String(result);
}
Or to put it a different way:
public static String hideNonGuesses(String input, Set<Character> guesses) {
char[] result = new char[input.length()];
for (int i = 0; i < result.length; i++) {
char c = input.charAt(i);
result[i] = guesses.contains(c) ? c : '-';
}
return new String(result);
}
(This could be done with Java 8 streams as well, but this is probably just as simple.)
Sample program:
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
Set<Character> guesses = new HashSet<>();
System.out.println(hideNonGuesses("apple", guesses));
guesses.add('p');
System.out.println(hideNonGuesses("apple", guesses));
guesses.add('o'); // No change - it's not in the word
System.out.println(hideNonGuesses("apple", guesses));
guesses.add('a');
System.out.println(hideNonGuesses("apple", guesses));
}
public static String hideNonGuesses(String input, Set<Character> guesses) {
char[] result = input.toCharArray();
for (int i = 0; i < result.length; i++) {
if (!guesses.contains(result[i])) {
result[i] = '-';
}
}
return new String(result);
}
}
Note that you're still looping over the input, and there may still be loops within Set.contains
(depending on the implementation) but it gets the result you want...
See more on this question at Stackoverflow