-
November 20th, 2011, 02:53 PM
#1
Hangman Java Code Error
Hey, I'm having a problem comparing a char to a String. The error is: char cannot be dereferenced. Any suggestions? I've put arrows around the line that holds the error.
Here's my code:
import java.util.*;
import java.util.Scanner;
/** Created by Shakiya Samantha Charles. This code will play one game of very simple hangman.
*/
public class Guess
{
public static void main(String[] args) throws Exception
{
Scanner console = new Scanner(System.in);
// Strings the word game for the fixed game.
String targetPhrase = "game";
String displayPhrase = "****";
String inputString;
char guess;
int position = 0;
// Prints welcome message and displays the asterisks.
System.out.println("Welcome to Hangman!");
System.out.println(displayPhrase);
while (displayPhrase.indexOf('*') != -1)
{
// Allows use to guess a letter.
System.out.println("Guess a Letter");
inputString = console.next();
guess = inputString.charAt(0);
position = targetPhrase.indexOf(guess, position+1);
if (position == -1)
System.out.println("Sorry - guess again!");
else
displayPhrase = displayPhrase.substring(0,position) +
guess +
displayPhrase.substring(position+1,displayPhrase.length());
System.out.println(displayPhrase);
{
// Displays a winning or losing message.
--------->> if (guess.equalsignorecase( targetPhrase )) <<-----------
System.out.print(" You won! The word is " + targetPhrase);
else
System.out.print("You lose! Muahahaha");
}
}
}
}
-
November 21st, 2011, 06:14 PM
#2
Re: Hangman Java Code Error
'guess' is a primitive of type char. You can't call methods on a primitive type - they are not objects.
You need to either convert the char to a String or convert the String to a char (which you can only do if the String contains exactly one character).
-
November 22nd, 2011, 07:57 AM
#3
Re: Hangman Java Code Error
it is easier to convert a character to a string one of the constructors in the string class takes the argument an array of characters. You can then use the equals method from the string class to compare two strings
-
November 22nd, 2011, 08:09 AM
#4
Re: Hangman Java Code Error
one of the most common mistake I've seen people do in Java is compare one string with another with an == sign this is the wrong approach as all variables in Java I mean the class variables are in essence pointers so what you're doing is comparing one pointer with another pointer please be mindful of this
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|