The complete program can use nearly the same code for the next two numbers as for the first number.
Here is the complete program. The differences in the code for each of the three numbers are highlighted in color. Noticing similarites like this often leads to better programs.
import java.util.Scanner;
class ComboLock
{
public static void main ( String[] args )
{
int lockFirst = 6,
lockSecond = 12,
lockThird = 30; // The combination
int numb; // a user-entered number
Scanner scan = new Scanner( System.in );
boolean correct = true;
//First Number
System.out.print("Enter first number: ");
numb = scan.nextInt();
if ( numb != lockFirst )
correct = false ;
//Second Number
System.out.print("Enter second number: ");
numb = scan.nextInt();
if ( numb != lockSecond )
correct = false ;
//Third Number
System.out.print("Enter third number: ");
numb = scan.nextInt();
if ( numb != lockThird )
correct = false ;
//Result
if ( correct )
System.out.println("Lock opens");
else
System.out.println("Lock does not open");
}
}
There are four if statements in this program.
Are these if statements nested?
(That is: is any if statement part of the
true branch or the false branch of another?)