Results 1 to 2 of 2
  1. #1
    carl is offline Member
    Join Date
    Jul 2007
    Posts
    35
    Rep Power
    0

    Default Help with if statement

    Hi, whenever I enter y or Y and call the method it should print out OK, but it doesn't it skips all the else if's and executes the last else statement "terminating" any suggestions why?I included the import java.lang.String
    Java Code:
    public void checkVariable()
    {
    if(checkString == "y" || checkString == "Y")
    {
    System.out.println("OK");
    }
    else if(checkString == "yes" || checkString == "Yes")
    {
    System.out.println("OK");
    }
    else if(checkString == "ok" || checkString == "OK")
    {
    System.out.println("OK");
    }
    else if(checkString == "sure" || checkString == "Sure")
    {
    System.out.println("OK");
    }
    else if(checkString == "why not?" || checkString == "Why not?")
    {
    System.out.println("OK");
    }
    else if(checkString == "n" || checkString == "N" || checkString == "no" || checkString == "No")
    {
    System.out.println("OK");
    }
    else
    {
    System.out.println("Terminating");
    }
    }
    Thanks.

  2. #2
    cruxblack is offline Senior Member
    Join Date
    Jul 2007
    Posts
    130
    Rep Power
    0

    Default

    Well, one thing u should realize, u are comparing a reference with a String value in every if clause u made
    Java Code:
    checkString == "y"
    the checkString holds the value of a reference, not the String "y", thats why it returns a false and what u get is the word "Terminating"
    Use the checkString.equals("y") to compare the value of a string

    Check this post for further details
    http://www.java-forums.org/java-tuto...va-string.html

Similar Threads

  1. there is no return statement
    By gabriel in forum New To Java
    Replies: 17
    Last Post: 12-03-2008, 05:55 PM
  2. Switch Statement Help
    By bluegreen7hi in forum New To Java
    Replies: 6
    Last Post: 02-06-2008, 06:16 AM
  3. goto statement
    By bugger in forum New To Java
    Replies: 2
    Last Post: 12-12-2007, 04:47 PM
  4. Statement or Prepared Statement ?
    By paty in forum JDBC
    Replies: 3
    Last Post: 08-01-2007, 05:45 PM
  5. If Statement
    By aDrizzle in forum New To Java
    Replies: 4
    Last Post: 07-08-2007, 09:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •