ATM pin verification in java - java

I am very new to programming and need some help. I need to write a simple program that verifies an ATM users pin number. The program will either, accept the pin and exit, tell the user it was an incorrect pin and have them try again up to three times, or tell the user their card is locked because they were wrong three times. I have searched for over an hour now and cannot find an example of this. I know i will need to use a scanner and a loop to accomplish this but not much else. Any help is appreciated as it is due by midnight......

for i = 1..3
prompt user for pin
read pin
check pin
if pin is correct, exit
tell user they were wrong and try again
tell user they got it incorrect three times and their card is locked.
I will give one hint which can trip some newbies up. The pin is an integer, right? So you might be tempted to use Scanner.nextInt() to get the input--do not do that! Just get the next line and compare Strings (you may have to use String.trim() to get rid of whitespace). It's more complicated if you try to use Scanner.nextInt() (what if the user enters something that cannot be parsed as an integer).

import java.util.Arrays;
import java.io.Console;
public class atm {
public static void main(String[] args) {
int counter = 3;
int attempt = 3;
char[] ch = null;
Console c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
String pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
while(!pass.equals("enigma") && attempt != 0){
System.out.println("Invalid PIN entered!. " + --attempt + " attempts remaining.");
counter--;
if(attempt != 0){
c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
}
else{
System.out.println("your card has locked!");
break;
}
}
}
}
Note that you can put your PIN code instead of "enigma" string, I hope that will help.

here is the implementation of pseudo code answered by #Jared above
boolean cardLockFlag = false ;
String password;
Scanner scan = new Scanner (System.in);
password = "password" ;
if(!cardLockFlag){
for(int i = 0 ; i < 3 ; i++){
if(password.equals(scan.next().trim())){
System.out.println("Success :) ");
break ;
}else{
if(i==2){
cardLockFlag = true ;
}else{
System.out.println("Wrong Password");
}
}
}
}else{
System.out.println("Card is Locked");
}

Related

Guessing Game Help :)

Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!

Java User Input Error Handling

I have simple java program that accepts 3 user inputs of type integer, double and string. I would like to know the best/most efficient way to perform error handling on all of these inputs in order to keep the program running, inform the user they have entered an incorrect input and ask them the question again . Any help would be greatly appreciated.
Here is my code
Scanner scan = new Scanner(System.in);
int inputInt;
double inputDbl;
String inputString;
System.out.print("Please enter a whole number: ");
inputInt = scan.nextInt();
System.out.print("Please enter a decimal number: ");
inputDbl = scan.nextDouble();
System.out.print("Please enter a string: ");
inputString = scan.next().toLowerCase();
Thanks for all the input people, you guys are awesome. I chose to just use a simple dowhile loop using a boolean trigger. I've tried using try catches before but ended up writing huge blocks of code to perform very basic input checks. So don't have any exception handling here, which I hope isn't gonna be necessary this way. Hopefully it doesn't break on me
do {
System.out.print("Please enter a whole number: ");
if (scan.hasNextInt()){
inputInt = scan.nextInt();
validInput = true;
} else
System.out.println("You have entered incorrect input! Please enter a whole number only");
scan.nextLine();
} while (validInput == false);
validInput = false;
do {
System.out.print("Please enter a decimal number: ");
......
......
Splitting this into n methods where n is how many user inputs there are.
For each user input create a method that gets the input:
String getStringInput(){
System.out.println("Enter input");
String input = scan.next();
//check the input to make sure it is correct
if(input.equals("foo")){
//if the input is incorrect tell the user and get the new input
System.out.println("Invalid Input");
//simply return this method if the input is incorrect.
return getStringInput();
}
//return the input if it is correct
return input;
}
For the main method that gets the input simply call the method:
void getAll(){
String stringValue = getStringInput();
}
This now makes it easy to get any number of inputs and check if the are correct.
boolean validated = false;
// this keeps user locked until he/she provides valid inputs for all variables
while(!validated) {
//get inputs here
// ..
// lastly
validated = validateLogic(inInt, inDbl, inStr);
}
// keep going
If you want to validate separately for each input, you shuold write while loop 3 times.

how to make a nested loop break if string.contains() is correct

I'm having issues understanding nested loops and their behavior. On the first loop the script asks for 10 digit number otherwise it will keep looping, this works fine. on the second loop, i'm trying to get the program to keep running until users enters "999" anywhere in the phone number. I have some idea but i'm not able to put it together. so if the user enters a 10 digit number but it doesnt contain 999, then it will keep asking to reenter phone number.
import javax.swing.JOptionPane;
import java.lang.*;
public class FormatPhoneNumber {
public static void main(String[] args) {
final int numLength=10;
String phoneNum = null;
String nineS="999";
phoneNum=JOptionPane.showInputDialog(null, "Enter your telephone number");
while (phoneNum.length()!=numLength)
{phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");
}
StringBuffer str1 = new StringBuffer (phoneNum);
str1.insert(0, '(');
str1.insert(4, ')');
str1.insert(8, '-');
JOptionPane.showMessageDialog(null, "Your telephone number is " +str1.toString());
while (phoneNum.contains(nineS))// THIS IS THE ISSUE
{
}
}
}
Use
if (phoneNum.contains(nineS))
{}
don't use
while (phoneNum.contains(nineS))
or U can do it this way
if (!(phoneNum.contains(nineS)))
{
JOptionPane.showMessageDialog(null,"Invalid Input");
}
Nesting is when one loop is inside another loop. The code you have provided does not have one.
Typical example of nesting:
while( some_condition )
{
do_something..
while( more_condition )
{
do_something_more..
}
}
If I understand correctly, you want to keep on entering numbers and do something with them. But once the user enters a number which has '999' in it, the control has to come out of the loops.
As someone already pointed out, you do not need nested loop to achieve this at all.
while( phoneNumber has 10 digits )
{
do_something..
if( phoneNumber has '999' anywhere )
{
break;
}
}
while (phoneNum.length()!=numLength)
{
phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");
StringBuffer str1 = new StringBuffer (phoneNum);
str1.insert(0, '(');
str1.insert(4, ')');
str1.insert(8, '-');
JOptionPane.showMessageDialog(null, "Your telephone number is " +str1.toString());
if(phoneNum.contains(nineS))// THIS IS THE ISSUE
break;
}
hope this helps.

Need help utilising the while loop for repeating parts of code

I am trying to use the while loop for re-running parts of code in my simple program. In this program, the user makes a simple account, types in a verification number, then signs in. Once signed in, I wish to allow the user to sign out, edit his profile settings and more. However I have a small problem.
Say the user has just edited their account settings. Instead of the program terminating, I want them to be able to return to the "menu".
The problem lies with how to do that. As there is no goto statement in java, from what I have read, I must use the while loop. I have no idea of how to go about that. I just can't wrap my head around it. Loops have always confused me. Also, should I even use the while loop? Would it be better to use the for or do-while loops? And what expression should I use? Will I need the break statement?
I know it isn't a concrete question, but any help that puts me on the right path is well appreciated.
Below is the full code for reference.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println("To confirm you are not a robot, please enter this code: " + randm);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You have placed a comment //where would I go if the user signed out?
The answer is, You will show the message to sign in when he is signed out, so that he can sign in again. You can do this by using for loop or loop or whatever loop you want. That means the part of user login will be in a loop, if the user logged in then the menu will be shown up. If the user sign out, the sign in form will be shown up infinitely.
You can put your code inside do. It will not break and will keep looping.
do{
}
while(true);

Password prompt and calling a method from an if statement

this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)

Categories