Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: If statement: ==/.equals() problems with .charAt()

  1. #1
    Junior Member Omnamah's Avatar
    Join Date
    Sep 2011
    Location
    England/Wales
    Posts
    29
    My Mood
    Inspired
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Question 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():
    if (guess.charAt(0).equals(actualWord.charAt(counter))){
    				isItCorrect = true;
    			}else{};

    This is the rest of the code, with '==' being used:
    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:
    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)
    This is a witty comment on the subject of Java programming.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default 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:
    if(isItCorrect = true){

    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).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member Omnamah's Avatar
    Join Date
    Sep 2011
    Location
    England/Wales
    Posts
    29
    My Mood
    Inspired
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: If statement: ==/.equals() problems with .charAt()

    Quote Originally Posted by aussiemcgr View Post
    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 View Post
    Furthermore, a quick overlook of your program gave me a red flag or two. Specifically with this line:
    if(isItCorrect = true){
    Aaah, cheers for pointing that out. An amateur mistake, xD. I hadn't gotten far enough down to refine that if statement yet.
    This is a witty comment on the subject of Java programming.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: If statement: ==/.equals() problems with .charAt()

    Your problem is with this statement:
    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().
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Problems with if else if statement operation
    By Farmer in forum Loops & Control Statements
    Replies: 4
    Last Post: May 29th, 2012, 06:43 AM
  2. problems with equals method.
    By mkarthik90 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 29th, 2012, 11:11 PM
  3. Using CharAt statement
    By CrimsonFlash in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 13th, 2011, 08:14 AM
  4. [SOLVED] If statement problems
    By SnarkKnuckle in forum Loops & Control Statements
    Replies: 2
    Last Post: January 6th, 2011, 11:51 PM
  5. what is charAt(0) ?
    By low1988 in forum Loops & Control Statements
    Replies: 5
    Last Post: October 11th, 2009, 10:03 AM