Results 1 to 3 of 3
  1. #1
    phil128 is offline Member
    Join Date
    Sep 2008
    Posts
    40
    Rep Power
    0

    Default comparing inputting strings from Joptionpane and if statement

    Is there anyway i can compare strings that i've enter using the JoptionPane. This is what i'm doing.

    class test{


    public static void main(String[] arguments)
    {

    String st;
    String st2 = "Exit";


    st = JOptionPane.showInputDialog("Enter exit to quit program");
    //Type exit

    if(st == st2){
    System.out.print("Exit program");
    }else{
    //Do something
    }
    }
    }

    I'm using the Eclipse Java Compiler 0.883_R34x, 3.4.1 under fedora 10 linux. Thank you for your time

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Search this forum (or any Java forum) on comparing Strings and you'll get an eye-full as it is one of the more common and persisting problems that we see, especially in new Java programmers. A key is that you don't want to use == to compare them but rather want to use the equals method.

    this:
    Java Code:
     if (st == st2)
    means that the two String objects, the one referred by st and the one referred by st2 are one and the same, but that's not what we're interested in here. Instead we want to know if the strings held by these two objects are the same, and that's why you must use equals or equalsIgnoreCase:
    Java Code:
     if (st.equalsIgnoreCase(st2))
    Last edited by Fubarable; 12-06-2008 at 07:50 PM.

  3. #3
    phil128 is offline Member
    Join Date
    Sep 2008
    Posts
    40
    Rep Power
    0

    Default

    Excellent! That worked. Thank you very much for your help and your time :-D.

Similar Threads

  1. Problem Comparing Strings (its not what you think)
    By hilather in forum New To Java
    Replies: 7
    Last Post: 11-19-2008, 07:43 PM
  2. Comparing Strings
    By souFrag in forum Advanced Java
    Replies: 5
    Last Post: 05-21-2008, 10:03 AM
  3. JSTL -- Comparing two strings for equality
    By trinkets in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 02-12-2008, 05:39 PM
  4. Comparing Strings
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-03-2007, 10:44 AM
  5. Statement or Prepared Statement ?
    By paty in forum JDBC
    Replies: 3
    Last Post: 08-01-2007, 05:45 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
  •