If statement: ==/.equals() problems with .charAt()
So I was reading through David J. Eck's fantastic and free Introduction to Programming Using Java, and he mentioned the .charAt() function within the String class. I got thinking how I could use this in a program to practice an array of techniques. I thought of the idea of making a text based Hangman game. I planned it all out (more or less, I still need to work out how I'll terminate the program once the user has guessed the entire word correct, and how to end it when they've run out of guesses), but I've come into some trouble with using the .charAt() function itself.
I had a similar problem to this before (and the brilliant members of this forum helped me work it out) where I was using '==' when I should have been using .equals(). I tried this in the code below (in the if statement inside the nested for loop) but it just stops the program from running at all.
I feel this is going to be something stupid... well, there is still the possibility that the whole structure of my program is off (it was late when I planned it, xD).
Any help would be very much appreciated, :). I'm on my summer holiday now so I'm keen to learn lots and lots of Java!
This was how I tried it with .equals():
Code :
if (guess.charAt(0).equals(actualWord.charAt(counter))){
isItCorrect = true;
}else{};
This is the rest of the code, with '==' being used:
Code :
import java.util.Scanner;
class HangmanGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String actualWord; //The word to be guessed.
String guess; //Hold the single letter guess.
boolean isItCorrect = false; // To determine whether the user should have the guess counted as failed, thus losing them a guess.
int counter;
int i;
//actualWord is given a value.
//Messages are displayed to the user.
System.out.println("Please enter the word you would like the other player to guess: ");
actualWord = input.nextLine();
System.out.println("Next player, guess the letters. The word contains " + actualWord.length() + " letters.");
//1st for loop = the "Guesses Loop": gets the result of isItCorrect from its nested for loop and then sorts out how many guesses are left.
//2nd for loop = does the actual comparing of guess to actualWord, cycling through each letter with charAt(counter).
for(i = 0; i <=10; i++){
isItCorrect = false; //reseting isItCorrect at the start of each guess, so that a 'Correct!' does not carry over to the next guess.
System.out.println("Please guess a letter: ");
guess = input.nextLine();
for(counter = 0; counter <= actualWord.length(); counter++){
if (guess.charAt(0) == actualWord.charAt(counter)){
isItCorrect = true;
}else{};
}
if(isItCorrect = true){
System.out.println("Correct! Letter " + guess + "found at index no. I DONT KNOW!" /*+ SOMEHOWGETTHEINDEXOFTHELETTER)*/);
counter = counter - 1;
}else{System.out.println("Incorrect. Attempts remaining: " + (10 - counter));}
}//end of 1st for loop; "Guesses Loop".
}
}
Output:
Code :
Please enter the word you would like the other player to guess:
cat
Next player, guess the letters. The word contains 3 letters.
Please guess a letter:
c
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at HangmanGame.main(HangmanGame.java:29)
Re: If statement: ==/.equals() problems with .charAt()
The String.charAt() method returns a char. Since chars are primitives (and really just an int), you can use == instead of .equals(). I'm not 100%, but I would assume the preferred way of comparing chars is with ==. You use .equals() with Strings because Strings are Objects.
Furthermore, a quick overlook of your program gave me a red flag or two. Specifically with this line:
That is an assignment, NOT a check. You either want to use a double-equals: if(isItCorrect==true), or don't bother with any equals: if(isItCorrect). Since isItCorrect is a boolean, if(isItCorrect) is the same as if(isItCorrect==true), just as if(!isItCorrect) is the same as if(isItCorrect==false).
Re: If statement: ==/.equals() problems with .charAt()
Quote:
Originally Posted by
aussiemcgr
The String.charAt() method returns a char. Since chars are primitives (and really just an int), you can use == instead of .equals(). I'm not 100%, but I would assume the preferred way of comparing chars is with ==. You use .equals() with Strings because Strings are Objects.
Cool, so my if statement is pretty much alright? I hate to sound amateur then, but do you know why it's dying at around that point? I'm completely lost if it's not a problem with the if statement.
Quote:
Originally Posted by
aussiemcgr
Furthermore, a quick overlook of your program gave me a red flag or two. Specifically with this line:
Aaah, cheers for pointing that out. An amateur mistake, xD. I hadn't gotten far enough down to refine that if statement yet.
Re: If statement: ==/.equals() problems with .charAt()
Your problem is with this statement:
Code java:
for(counter = 0; counter <= actualWord.length(); counter++){
This is a very common mistake. String.length() returns the number of characters in a String. In your example input: "cat", the length of it is 3. However, the indexes start at 0 and end at length-1 (this applies to Strings as well as Arrays and Lists). So the last index in the word "cat" would be 2 (index 0 = "c", index 1 = "a", index 2 = "t").
Your loop, however, says you want to start at 0 and end AFTER index 3 (ex: while(counter <= "cat".length()), where "cat".length() = 3). What you actually want to do is loop UNTIL index 3. To do that, all you have to do is remove the = sign. So instead of checking while counter <= actualWord.length(), you want to check while counter < actualWord.length().