Compare two strings in an array

Hello!
Please feel free to give me hints, but do not give me any code.
Ok, here is what I am trying to do, I whant to compare my input string whith strings allready stored in the array. If my input string equals any of the allready excisting strings, a error wil show upp, otherwise store the new string in next avalibal position. I do not seem to get the method right for comparing the strings. here is the method I have written so far, please take a look and give me a hint, but no code. :)
//Check if a user already excists     
public void compareNames (People in_array [], String in_name) {
          for (int i=0; i<value.peopleCount; i++) {
               if (in_name.equals(in_array.getPeople())) {
               System.out.print("The user already excist, please chose another name");
}value.peopleCount is an global count value for people arays.
getPeople get the name from the people class.
Martin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

A couple notes here.
The name compareNames() is misleading if it is going to do what you described. A comparison will generally not have side-effects like outputting error messages to the console or adding new items to an array. It would be better if you called the method addIfNew(), and returned a boolean indicating whether the name was new or not. The caller would then be responsible for displaying an error message if the method returned false.
I also suggest you use a List such as ArrayList instead of an array, otherwise you will have to resize and copy your array every time you add something to it that exceeds the array size, and will allow you to do away with the global peopleCount.

Similar Messages

  • Compare two strings for partial or full match

    I have been trying to figure out away of comparing two strings.
    I can get the full string matching to successfully work but am struggling on how to get partial eg wildcard search working.
    say I had names like paul Duncan, George Morrison.
    I have split them up so its now paul , duncan i then use the users entered string to compare it against the name name to see if it matches anything in the first name or the last name if it does i added it to an arraylist.
    however i have tried t use a indexof as i believe this looks for similarity (Substring matches?) but it always returns -1.
    Could anyone possibly direct me to a method that will allow me to use partial text string to match it against stored user names.
    eg user enters pa
    I would return anything that would contain pa
    thanks for any help

    thank you for the reply
    Sorry I forgot to put in the code.
    This is a reduced down version including the read in from a text file as well as the index of if statement and the adding of it to an array list.
    public class FindContact {
    String res;
    /** Creates a new instance of FindContact */
    public FindContact() {
    public Object[] FindAUser(String passSearch) {
    System.out.println("getting here");
    ArrayList found = new ArrayList();
    String patternStr = ",";
    int j, i = 0;
    try {
    BufferedReader in = new BufferedReader(new FileReader("H:\\out.txt"));
    String str;
    while ((str = in.readLine()) != null) {
    String[] fields = str.split(patternStr);
    //for(j=0;j < fields.length;j++) {
    if (fields.length != 0) {
    if (passSearch.indexOf(fields[0])!=-1 || passSearch.indexOf(fields[1])!=-1) {
    found.add(str);
    System.out.println("ENDDDDDDDD value ");
    in.close();
    } catch (IOException e) {
    System.out.println(e.toString());
    Object[] foundResult = new Object[found.size()];
    foundResult = found.toArray();
    if (foundResult.length >= 0) {
    System.out.println(foundResult.length);
    return foundResult;
    Hope that helps as it has confused me and am not sure why it is not returning a value.
    Should I maybe use the contain method instead to search for the user inputted string?

  • How to Compare two strings in PL/SQL

    Hi All,
    I need to compare two strings whether they are equal or not in PL/SQL.Is there any function to comparing the strings.

    Yes, the = sign.
    Are you after something like:
    IF v_string1 = v_string2 THEN
    ELSE
    END IF;?
    Edited by: Boneist on 27-Aug-2009 11:41

  • Failed to compare two elements in the array

    very often, I have the error "Failed to compare two elements in the array" in Exchange 2013 ECP. We are not running DAG. I google a bit but don't get a lot of result on this.
    I was trying to track mail from a user who send to DL group. Since I can't do in in ECP , how can I do it in EMS?

    I too have this issue.  I'm not sure how wide spread.  I know of one user who sends emails regularly to a DL named "All Users" which is a Security Group which we then add real users to and not just every mailbox.  When he sends the emails,
    from his perspective, everything is fine, meaning he gets to NDR or anything.  Also, when he adds the Dl in Outlook To field and expands it, all the correct users are there.  In fact, it tells him there are 203 addresses here.  However, only
    184 are actually getting the message.  When I try the EAC to view the tracking report, it will show the message, but if I click on the edit button, I get "Failed to compare two elements in the array".  If I try from EMC with search-messagetrackingreport
    -identity "recipient address" -sender "sender address" -bypassdelegatechecking and the recipient address is the group, it says it could not be found.  If I try with simply putting an email address of someone who is a member of that group, it says Warning:
    An unexpected error has occured and a Watson dump is being generated.  Failed to compare two elements in the array.  I don't know what else to try.  Anybody??

  • Compare two string in different line in textarea

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
                        public TextCounterPanel() {
                        setBackground(Color.DARK_GRAY);
                        textInput = new JTextArea();
                        textInput.setBackground(Color.WHITE);
                        JPanel south = new JPanel();
                        south.setBackground(Color.DARK_GRAY);
                        south.setLayout( new GridLayout(4,1,2,2) );
                             JButton countButton = new JButton("Process the Text");
                             countButton.addActionListener( new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       processInput();
                             south.add(countButton);
                        lineCountLabel = new JLabel(" Number of lines:");
                        lineCountLabel.setBackground(Color.WHITE);
                        lineCountLabel.setForeground(Color.BLUE);
                        lineCountLabel.setOpaque(true);
                        south.add(lineCountLabel);
                        setLayout( new BorderLayout(2,2) );
                        setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
                        JScrollPane scroller = new JScrollPane( textInput );
                        add(scroller, BorderLayout.CENTER);
                        add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel
    How can I compare two string in different line in text area

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
    public TextCounterPanel() {
    setBackground(Color.DARK_GRAY);
    textInput = new JTextArea();
    textInput.setBackground(Color.WHITE);
    JPanel south = new JPanel();
    south.setBackground(Color.DARK_GRAY);
    south.setLayout( new GridLayout(4,1,2,2) );
    JButton countButton = new JButton("Process the Text");
    countButton.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    processInput();
    south.add(countButton);
    lineCountLabel = new JLabel(" Number of lines:");
    lineCountLabel.setBackground(Color.WHITE);
    lineCountLabel.setForeground(Color.BLUE);
    lineCountLabel.setOpaque(true);
    south.add(lineCountLabel);
    setLayout( new BorderLayout(2,2) );
    setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
    JScrollPane scroller = new JScrollPane( textInput );
    add(scroller, BorderLayout.CENTER);
    add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel

  • Compare two strings in a formula

    Hi,
    I'd like to know if there's a way to compare two strings in a formula ?
    I have this consition:
    IF(@SUBSTRING(@NAME(@CURRMBR(TIME_FROM)),5)==@NAME(@CURRMBR(TIME)))
    But the == operator can only compare two data.
    Thanks,
    Cyril

    Hi,
    thank you both for your answers.
    When I figured that the == operator was for data only, I didn't even try to compare member names.
    I finally used the solution that Cameron suggested in another conversation. I created a date measure, and loaded some data since the beginning of my time to the end.
    It starts in 1974 (annually), then becomes monthly data, and then daily data from 2009, so it's not so many blocks to br created. In the end I have the same value for "from 2008"/"from Apr 30", and I can easily compare my dates.
    Note that I could have also used the @TODATE function, which turns a date into a number, but the format of date is limited and doesn't fit the format of my member names, so I got lasy... and I'm not sure my users would have apreciated that ;)
    Thanks, this post is solved.
    Cyril

  • Compare two strings and the save the greater

    To devolop a vi,it can compare two strings.A string is gived,the other is saved previously.If greater,then save,or do nothing.

    Hi,
    I am assuming by "greater" you mean the string length.
    Use the string length function from the strings palette, with shift-registers on a while loop. Write to the shift-register the "greater" string.
    I am attaching a diagram screenshot for this. NOTE: depending on how you want this VI to run, you can move the input and output string control and indicator inside our outside the while loop.
    Hope this is what you were looking for.
    Khalid
    Attachments:
    strlen.gif ‏17 KB

  • How to compare two strings whether both are equal while ignoring the difference in special characters (example: & vs & and many others)?

    I attempted to compare two strings whether they are equal or not. They should return true if both are equal.
    One string is based on Taxonomy's Term (i.e. Term.Name) whereas other string is based on String object.
    The problem is that both strings which seem equal return false instead of true. Both string values have different special characters though their special characters are & and &
    Snapshot of different design & same symbols:
    Is it due to different culture or language?
    How to compare two strings whether both are equal while ignoring the difference in special characters (& vs &)?

    Hi Jerioon,
    If you have a list of possible ambiguous characters the job is going to be easy and if (& vs &) are the only charracters in concern awesome.
    You can use the below solution.
    Before comparing pass the variables through a replace function to standarize the char set.
    $Var = Replace($Var,"&","&")
    This is going to make sure you don't end up with ambiguous characters failing the comparison and all the char are "&" in this case.
    Similar technique is used to ignore Character Cases 'a' vs. 'A'
    Regards,
    Satyajit
    Please “Vote As Helpful”
    if you find my contribution useful or “Mark As Answer” if it does answer your question. That will encourage me - and others - to take time out to help you.

  • Comparing two strings

    How do you check to see if two strings have dashes in the same places?
    For example:
    String one= "dfsdt-ra-s-dsfd";
    String two= "dsfst-da-s-dsfd";
    would return true.
    String one="jhsdjfk-dsf-sdf"
    String two="d-dsf-dfsf-f"
    would return false.
    This is what i have:
    if (one.indexOf("-") == two.indexOf("-")) {
    return true;
    The problem with this if statement is it only checks the first time the dash come and not the whole string.
    How can I check the whole string to compare the index of string one and string two every time the dash come up.

    Hey,
    Check this code out, compile it and you should get it. Let me know if you have any questions.
    Thanks
    Riz
    public class StringCheck {
         String s1;
         String s2;
         boolean AreEqual;
         int lens1,lens2;
         public StringCheck(){
              s1="dfsdt-ra-s";
              s2="dfsdt-ra-s";
              AreEqual=false;
              lens1=s1.length();
              lens2=s2.length();
         public boolean CheckTheString(){
              boolean localcheck=false;
              if(lens1==lens2){
                   for(int i=0;i<lens1;i++){
                        if(s1.charAt(i)==s2.charAt(i)){
                             localcheck=true;
                             i++;
                        if(s1.charAt(i)!=s2.charAt(i)){
                             return false;
              if(localcheck)return true;
              else return false;
              //return true;
         public static void main(String args[]){
              StringCheck c = new StringCheck();
              boolean validate=c.CheckTheString();
              if(validate)
                   System.out.println("The string are equal");
              else
                   System.out.println("The String are not equal");
    }

  • Compare two strings and verify they have same alphabets

    If i have two strings....s and t. I want to return whether s contains every letter in t. For example, "abcd" contains all the letters in "bbdc", since every letter in the second string appears in teh first.
    thanx

    If i have two strings....s and t. I want to return
    whether s contains every letter in t. For example,
    "abcd" contains all the letters in "bbdc", since every
    letter in the second string appears in teh first.This will do the job in s.length()*t.length() steps.
    //  Indicates whether s contains every letter in t.
    boolean allCharsContainedIn(String s, String t) {
        int len = t.length();
        for (int i = 0; i < len; i++) {
            if (s.indexOf(t.charAt(i) == -1)
                return false;
        return true;
    }S&oslash;ren

  • Compare two String

    String s1 = "ABC";
    String s2 = "ABC";
    *if (s1 == s2){*     //This tests true
    *if (s1.equals(s2)){*     //This tests true
    *if (s1.equalsIgnoreCase(s2)){*//This tests true
    My understanding is s1 refers one String object with the value ("ABC"); while s2 refers another String object with the value ("ABC"); So s1 and s2 actually refers to different objects.
    Is this correct?
    If so why the above test true?
    Thanks
    Scott

    Just to dig a little further...
    For
    String s1 = "ABC";
    and
    String s1 = new String("ABC");
    You mentioned:
    if((Object)s1 == (Object)s2){
    return true;
    should return false because the two String Object references s1 and s2 are stored at different memory locations*
    --My question, the fact that the comparision of ((Object)s1 == (Object)s2){... returning  false is:
    1) because they refer to different objects which are stored ar different locations?
    OR
    2) due to the above said: two String Object references s1 and s2 are stored at different memory locations
    --I prefer the 1).  But not so sure.
    --If answer is 2),  it will contradicts in following for s1 and s2 are stored at the different locations but the comparision ((Object)s1 == (Object)s2  will return true, i.e.,
    String s1 = "ABC";
    String s2 = "ABC";
    uses String.intern at compile time
    so
    s1 reference at aaa looks for the String object at xxx
    s2 reference at bbb looks for the String object at xxx
    this way
    if((Object)s1 == (Object)s2){
    return true;
    } should return true....
    Further,
    String s1 = "abc";
    String s3 = s1;
    Now, both s1 and s3 refer to the same Object ("abc"), but s1 and s3 are stored at different locations. Yet,
    if (s1 == s3)... will return true.
    This further indicates that the comparision of two references only has something to do with the actual location of the object, not the location of the reference itself.
    Like to get your opinion on this issue.
    Thanks
    Scott

  • Problem in comparing Two String

    Hi friends
    I have a strange Problem, i am able to find out the Reason for this problem.
    In my Program i use a JTextField with implements the FocusListener. i just get the Text of this JTextField and retrive a record from DataBase which is Equal to the JTextField's Text. yes it retrives the same record. Now i want to compare these two Text. I mean the JTextFied text and the text which i retrived from the Database.
    My code is this
    public void focusLost (FocusEvent fe) {
              Object obj = fe.getSource ();
          if (obj == txtMemberId)
                        memberId = txtMemberId.getText().toString();     
                        int memberDays,memberBooks,memberCat,heldBooks;
                        String mname,memberNo;                              //Use for Comparing the Member's Id.
                        boolean find = false;                         //To Confirm the Member's Id Existance.
                        try
                             //SELECT Query to Retrieved the Record.
                             String q = "SELECT * FROM Members WHERE RollNumber= '"+memberId+"'";
                             ResultSet rs = st.executeQuery (q);     //Executing the Query.
                             rs.next ();                    //Moving towards the Record.
                             memberNo = rs.getString ("RollNumber");
                                                                //Storing the Record.
                             boolean ans=memberNo.equals(memberId);
                             System.out.println("STAUS OF THE COMPARISION:"+ans);
                             if (ans)
                             {               //If Record Found then Display Records.
                             System.out.println("RECORD FOUND DON'T WORRY");
                             find = true;
                             memberCat=rs.getInt("MCat");
                                  heldBooks=rs.getInt("Bcnt");
                                  System.out.println("HELD BOOK COUNT IS::"+heldBooks);
                                  mname=rs.getString ("FirstName");
                                  txtMemberName.setText (""+mname);
                                  gblname=mname;
                                  rs.close();
                                  ResultSet rs1= st.executeQuery("Select * from Mecat where MCat = " + memberCat + "" );
                                  rs1.next();
                                  memberBooks=rs1.getInt("Blmt");
                                  System.out.println("BOOK LIMITED TO::"+memberBooks);
                                  memberDays=rs1.getInt("Dlmt");
                                  if(heldBooks==memberBooks)
                                       txtClear();
                                       JOptionPane.showMessageDialog (this, "Book Limit Reached");
                                       dispose();
                                   GregorianCalendar gcal=new GregorianCalendar();
                                     id1= gcal.get(Calendar.DATE);
                                     im=(int)gcal.get(Calendar.MONTH)+1;
                                     iy=gcal.get(Calendar.YEAR);
                                     vd=id1+memberDays;
                                     vm=im;
                                     vy=iy;
                                     String xx,yy,zz;
                                     if(id1<10) {
                                         xx="0"+id1;
                                     } else {
                                         xx = ""+id1;
                                     if(im<10) {
                                         yy="0"+im;
                                     } else {
                                         yy = ""+im;
                                     idate=xx+"/"+yy+"/"+iy;
                                     //  String vdate=vd+"/"+vm+"/"+vy;
                                     //********************                        to calcutlate return date
                                     //System.out.println("came here1!!!");
                                     while(vd>31) {
                                         if(im==1||im==3||im==5||im==7||im==8||im==10||im==12){
                                             if(vd>31){
                                                 im=im+1;
                                                 vd=vd-31;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;
                                         if(im==4||im==6||im==9||im==11){
                                             if(vd>30){
                                                 im=im+1;
                                                 vd=vd-30;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;}
                                         if(im==2){
                                             if(vd>28){
                                                 im=im+1;
                                                 vd=vd-28;
                                                 if(im>12){
                                                     im=im-12;
                                                     iy=iy+1;
                                    vdate = vd+"/"+im+"/"+iy;
                                 //System.out.println("came here3!!!");
                             //     txtMemberId.setText ("" + memberId);
                                  txtDate1.setText(idate);
                                  txtDate2.setText(vdate);
                             else {
                                  find = false;
                                  if (find == false) {
                                  JOptionPane.showMessageDialog (this, "Really Record not Found.");
                                  System.out.println("DON'T WORRY FIND A WAY");
                        catch (SQLException sqlex) {
                             if (find == false) {
                                  //txtClear ();          //Clearing the TextFields.
                                  JOptionPane.showMessageDialog (this, "Really Record not Found.");
                                  txtDate1.setText("");     
                                  txtDate2.setText("");
                                  txtMemberId.setText("");
                                  txtMemberId.requestFocus ();
                        catch(Exception e)
                             e.printStackTrace();
    when i compare those two Text By using this Line
    boolean ans=memberNo.equals(memberId);[b]It retruns False
    please tell me what would be the Problem here
    Thank you for your service
    Cheers
    Jofin

    Hi
    Thank you very much, it is working for me. i am very greatful to you .
    Thank you for your service
    jofin

  • Why i can't  compare two string

    * @(#)Assignment.java 1.0 03/12/12
    * You can modify the template of this file in the
    * directory ..\JCreator\Templates\Template_1\Project_Name.java
    * You can also create your own project template by making a new
    * folder in the directory ..\JCreator\Template\. Use the other
    * templates as examples.
    //package myprojects.assignment;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    * MainForm.java
    * Created on 12 December 2003, 16:27
    * @author Akasha
    public class Assignment extends javax.swing.JFrame {
         private String myname;
    private String utxtname,ptxtpass;
    /** Creates new form MainForm */
    public Assignment() {
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
         //     JText = new JFormattedTextField();
         jButton1 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    getContentPane().setLayout(null);
              getContentPane().setBounds(800,800,800,800);
    addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    formMouseClicked(evt);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jButton1.setBackground(new java.awt.Color(0, 0, 255));
    jButton1.setForeground(new java.awt.Color(204, 255, 255));
    jButton1.setText("Login");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    jButton1MouseClicked(evt);
    getContentPane().add(jButton1);
    jButton1.setBounds(110, 160, 70, 30);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(220, 70, 150, 20);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(220, 100, 150, 20);
         //     getContentPane().add(JFormattedTextField1);
              //JFormattedTextField.
    jLabel1.setText("User Name");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(60, 70, 150, 16);
    jLabel2.setText("Password");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(60, 100, 160, 16);
    pack();
    private void formMouseClicked(java.awt.event.MouseEvent evt) {
    // Add your handling code here:
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
         myname="mazhar";
         utxtname = jTextField1.getText();
         if (myname == utxtname)
                   JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
              else if (myname != utxtname)
                   JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);
    // Add your handling code here
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
         Assignment assign =new Assignment();
         //width and hight
         assign.setSize(400, 175);
    assign.show();
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration

    Basic java. I think that you need to read the tutorial... ;-) http://java.sun.com/docs/books/tutorial/
    BAD (yours): you are comparing objects (ref to objects -> always differents even if there contains the same thing)
    ==========
    if (myname == utxtname) {
    JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
    } else if (myname != utxtname) {
    JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);
    GOOD (mine):
    ===========
    if (myname.equals(utxtname)) {
    JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
    } else {
    //if (!myname.equals(utxtname)) {
    JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);

  • Why i can compare two string

    * @(#)Assignment.java 1.0 03/12/12
    * You can modify the template of this file in the
    * directory ..\JCreator\Templates\Template_1\Project_Name.java
    * You can also create your own project template by making a new
    * folder in the directory ..\JCreator\Template\. Use the other
    * templates as examples.
    //package myprojects.assignment;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    * MainForm.java
    * Created on 12 December 2003, 16:27
    * @author Akasha
    public class Assignment extends javax.swing.JFrame {
         private String myname;
    private String utxtname,ptxtpass;
    /** Creates new form MainForm */
    public Assignment() {
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
         //     JText = new JFormattedTextField();
         jButton1 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    getContentPane().setLayout(null);
              getContentPane().setBounds(800,800,800,800);
    addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    formMouseClicked(evt);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jButton1.setBackground(new java.awt.Color(0, 0, 255));
    jButton1.setForeground(new java.awt.Color(204, 255, 255));
    jButton1.setText("Login");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    jButton1MouseClicked(evt);
    getContentPane().add(jButton1);
    jButton1.setBounds(110, 160, 70, 30);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(220, 70, 150, 20);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(220, 100, 150, 20);
         //     getContentPane().add(JFormattedTextField1);
              //JFormattedTextField.
    jLabel1.setText("User Name");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(60, 70, 150, 16);
    jLabel2.setText("Password");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(60, 100, 160, 16);
    pack();
    private void formMouseClicked(java.awt.event.MouseEvent evt) {
    // Add your handling code here:
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
         myname="mazhar";
         utxtname = jTextField1.getText();
         if (myname == utxtname)
                   JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
              else if (myname != utxtname)
                   JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);
    // Add your handling code here
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
         Assignment assign =new Assignment();
         //width and hight
         assign.setSize(400, 175);
    assign.show();
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration

    Basic java. I think that you need to read the tutorial... ;-) http://java.sun.com/docs/books/tutorial/
    BAD (yours): you are comparing objects (ref to objects -> always differents even if there contains the same thing)
    ==========
    if (myname == utxtname) {
    JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
    } else if (myname != utxtname) {
    JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);
    GOOD (mine):
    ===========
    if (myname.equals(utxtname)) {
    JOptionPane.showMessageDialog(null,"This is"+ utxtname + myname+ " first ","Welcome",JOptionPane.INFORMATION_MESSAGE);
    } else {
    //if (!myname.equals(utxtname)) {
    JOptionPane.showMessageDialog(null,"This is"+ myname+ "first action","Welcome",JOptionPane.INFORMATION_MESSAGE);

  • Compare two strings...

    Hi,
    I have something like this, where book.cost( ) is a string that already existes an pages is another string with the number the user inserts. And no, unfortunatly I cannot do it with integers... How can I copare the value of both? thanks
    if (book.cost( ) > pages){
    book.print();
    }else{
    System.out.println("Any book with more than "+pages+" was found");
    }

    Looks like you're doing the same coursework as me Kikens! I agree that they should both definately be int's, but apparently he wants us to use strings instead. No idea why though. The parseint method works fine for it, as long as you've entered a number that can be turned into a integer earlier - I've used a try-catch loop to return an error if it's not an integer.

Maybe you are looking for