user2999980 user2999980 - 2 months ago 6
Java Question

Data validation in Java

Well let's just say that this used to work fine then I started it up again today and now it doesn't....

pin is 1234 and no matter what I do it says it's not valid...

and yes I know that it doesn't check the third time. I have to fix that too:

import java.util.Scanner;

import java.util.Scanner;


public class ATM
{

public ATM()

{
Scanner console = new Scanner(System.in);

final String pin = "1234";
String userPin = "";
int pinCount = 1;
boolean error = false;

do{
System.out.print("Enter PIN: ");
userPin = console.nextLine();

if (pinCount == 3) {
System.out.println("Bank account is blocked");
break;
}
else if (userPin.length() < 4 || userPin.length() > 4) {
error = true;
pinCount += 1;
}
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
else{
System.out.println("Your PIN is incorrect");
error = true;
pinCount += 1;
}
}while(error);
}

public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}


Don't ask me why I have it split:

public class ATMtest
{
public static void main(String[] args)
{
ATM atm = new ATM();
}

}


Any help would be greatly appreciated.

Answer

You don't compare String objects with ==. You should use the equals() method. I know it does not make sense if you are new in java but == means "are they the same reference?" and equals() means "are they equal?".