-
If statement help
Code:
public class Transaction
{
// instance variables - replace the example below with your own
private Integer amount;
private Integer balance;
/**
* Constructor for objects of class Transaction
*/
public Transaction()
{
// initialise instance variables
balance = 0;
amount = null;
}
public void makePayment(Account acRef, Integer AccountNumber, Integer SortCode, Integer paymentAmount, String paymentTo)
{
if((AccountNumber == acRef.getAccountNumber())&&(SortCode == acRef.getSortCode())){
//compares account number and sort code entered in the parameter to the account number and sort code currently
// held in the Account class through .getAccountNumber
amount = paymentAmount;
String place = paymentTo;
if(balance <= 0){
System.out.println("You do not have sufficient funds to make this transaction");
}else{
balance = balance - amount;
System.out.println("Payment of £" + amount + "to " + place);
}
}else{
System.out.print("Incorrect account number or sort code");
}
}
My if statement in my Transaction class checks to see if the account number and sort code entered by the user is correct, then they can proceed to make the payment, else an error message pops up. However every time i enter the correct account number and sort code which I previously entered in my Account class the error message still pops up :s.
Help please:(-:
-
Re: If statement help
If you're comparing strings use .equals() and not ==
-
Re: If statement help
But my account number parameter is an Integer so how would i use .equals()
-
Re: If statement help
Now that you edited it you can't use .equals() anymore. ;)
Besides that I can't really see a problem with the if-statement.
-
Re: If statement help
we'd have to see the Account class... I would ask why you're using Integer instead of the primitive int. Is this a requirement? Integer is an Object, so has a .equals(). Luckily someone overrode the Object.equals() with one that checks integer values and not memory location. :)
If you run this:
Code:
Integer x = new Integer(2);
Integer y = new Integer(2);
int a = 2;
int b = 2;
if(x.equals(y)){
System.out.println("x equals y"); // this will print
}
if(x == y){
System.out.println("x=y"); // this will NOT print
}
if(a == b){
System.out.println("a=b"); // this will print
}
you'll see that x == y is not true! Use the primitive int! (or .equals)
-
Re: If statement help
... To add the confusion:
Code:
Integer x = new Integer(2);
int a = 2;
if(x == 2){
System.out.println("x = 2"); // this prints
}
if(x == a){
System.out.println("x=a"); // this prints!
}
Bottom Line: avoid Integer, Double, Float, Boolean objects unless you really cannot!
Edit: Reasons to use Integer include (but are not limited to) using anywhere a generic is needed i.e. ArrayList<Integer> as ArrayList<int> will not work!