i'm essentiel trying to create a movie guessing game, a bit like hangman, but you need to guess a movie title. The movie title is encoded with each character being represented by the underscore ('_') character. As the user inputs a correct letter, the underscore at the position of the corresponding letter changes to that letter. The user inputs his guesses as single chars using the scanner. My problem is that some movie titles contain a space (' '). But I am unable to use the scanner to return a space... My guess is that a scanner uses the whitespace as the default delimiter therefore it doesn't return a space as a character because it uses the whitespace to break the input into tokens?
By 'return a space' I mean consider a space as a input, and not as a delimiter.
Can anyone give me a solution as to how I could detect a space from the user input?
This code should read through the movieTitle, then if the movie title contains a space at index i, and the user input is a space, then the codedMovieTitle should update with a space at position i, instead of an underscore. However this doesn't work. When I enter a space using the scanner nothing happens...
for (int i = 0; i < movieTitle.length(); i++) {
if(Character.isSpaceChar(movieTitle.charAt(i)) &&
Character.isSpace(userInput)){
encodedMovieTitle = encodedMovieTitle.substring(0, i)
+ userInput
+ encodedMovieTitle.substring(i + 1);
}
}
This is the code for my scanner:
Scanner scanner = new Scanner(System.in);
char userInput;
while(!gameIsWon && (numberOfGuessesLeft != 0)) {
while (scanner.hasNextInt()) {
System.out.println("You must enter a single character, try again.");
scanner.next();
}
userInput = scanner.nextLine().charAt(0);
I am also struggling with enabling my scanner input to be non case sensitive. Some of the movies have capital letters in them. If the title is "Snowstorm" and the user inputs the character 's', the resulting encodedMovieTitle will be "_ _ _ _ s _ _ _ _", not "S _ _ _ s _ _ _ _"
If anyone has a solution that would be great! Most solutions I found involved using strings but I use chars as my userInput etc therefore I was wondering if there's a solution involving chars.
Code for checking is userInput (char) is in movieTitle (string):
for (int i = 0; i < movieTitle.length(); i++) {
if (updatedCodedMovieTitle.charAt(i) != userInput && movieTitle.charAt(i) == userInput) {
updatedCodedMovieTitle = updatedCodedMovieTitle.substring(0, i)
+ userInput
+ updatedCodedMovieTitle.substring(i + 1);
wordHasBeenUpdated = true;
}
if(Character.isSpaceChar(movieTitle.charAt(i)) && Character.isSpaceChar(userInput)){
updatedCodedMovieTitle = updatedCodedMovieTitle.substring(0, i)
+ " "
+ updatedCodedMovieTitle.substring(i + 1);
}
}