Riley
Riley

Reputation: 33

How to use !.equals with strings?

We're working on a group assignment. Part of the program is for the use to input "pay", followed by the student's SIN (social insurance number) and how much to deduct their account by. For example, pay,193678187,900.

The SIN is compared to a list of SINs from a file, generated into an array and compared, curSin.equals(stuSin)). curSin and stuSin are both Strings.

If the SIN is found, it will reduce the ammount from the student's balance (not shown) and write it to the file write(student,inrec).

If the SIN isn't found, it should return "SIN not found".
Our problem is that even if the SIN is found, it still returns "SIN not found". We think it has something to do with the if statement and the not equals comparison, but we've tried everything we can think of and can't get it to work properly.

Any help would be greatly appreciated. Thanks.

Code snippet below.

    if (cmd.equals("pay") && p.length == 3)
    { // first word is "pay";three terms (cmd, sin, $)
        System.out.println("pay");
        // Pay: decreases student payment, notifies of overpayment
        String stuSin = p[1];
        double stupay = Double.parseDouble(p[2]);
        for (int i = 0; i < student.length; i++)
        {
            Student x1 = student[i];
            String curSin = x1.getSin();
            if (curSin.equals(stuSin))
            {
                double curpay = x1.getBal();
                double newBal = curpay - stupay;
                if (stupay > curpay)
                {
                    JOptionPane.showMessageDialog(null, "Overpayment");
                    System.exit(0);
                }
                x1.setBal(newBal);
                System.out.println(x1.getBal());

                write(student, inrec);
            }
            else if (!curSin.equals(stuSin))
            {
                JOptionPane.showMessageDialog(null, "SIN not found"); // sin not found
                System.exit(0);
            }

        }// end of for loop
    }

Upvotes: 3

Views: 2990

Answers (2)

jahroy
jahroy

Reputation: 22692

There doesn't appear to be anything wrong with your use of the equals method.

You should add a couple debug statments (or actually use a debugger) to make sure that you're really comparing the strings you want.

System.out.println("stuSin: '" + stuSin + "'");
System.out.println("curSin: '" + curSin + "'");

Upvotes: 3

emory
emory

Reputation: 10891

It looks like your program would work correctly if the first in the list was a correct match.

But the first is not a correct match. So it exits without ever looking at the second.

You probably want to iterate over all students and the first time it matches break out of the loop.

If and only if you iterate over all students without matching run the JOptionPane.showMessageDialog(null,"SIN not found"); //sin not found

Upvotes: 5

Related Questions