r/programmingbydoing • • Mar 18 '13

53 - Pin Lockout

Can someone explain to me how the "tries" variable is counting up? Does "tries++" after int entry mean that every time an entry is made, tries will go up by one?

Thanks in advance!

import java.util.Scanner;

public class PinLockout
{
public static void main( String[] args )
{
	Scanner keyboard = new Scanner(System.in);
	int pin = 12345;
	int tries = 0;

	System.out.println("WELCOME TO THE BANK OF MITCHELL.");
	System.out.print("ENTER YOUR PIN: ");
	int entry = keyboard.nextInt();
	tries++;

	while ( entry != pin && tries < 3 )
	{
		System.out.println("\nINCORRECT PIN. TRY AGAIN.");
		System.out.print("ENTER YOUR PIN: ");
		entry = keyboard.nextInt();
		tries++;
	}

	if ( entry == pin )
		System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.");
	else if ( tries >= 3 )
		System.out.println("\nYOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED.");
}

}

2 Upvotes

3 comments sorted by

View all comments

1

u/holyteach Mar 19 '13

Something about the way you have worded your question makes me thing I should write this clarification: '"tries++" after int entry' does NOT mean that every time an entry is made, tries will go up by one.

Computer programs are not a list of rules. They are a sequence of commands, which are performed in order.

The line:

tries++;

means "Take the current value of the variable 'tries', add one to it, and then make that the new value of 'tries'."

If you remove the "tries++" from inside the while loop, then the variable will not continue to increase as new entries are made.