Home

Formulating Expressions

 

Counting and Looping

 

While a Statement is True

The Java language provides various keywords that allow you to conditionally control data input and output. These controls are referred to as loops.

The while statement examines or evaluates a condition. The syntax of the while statement is:

while(Condition) Statement;
Flowchart: while
  

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop.

Here is an example:

int number = 0;
	
while( number <= 12 )
{
            System.out.print("Number ");
            System.out.println(number);
            number++;
}

To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to get a value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

Second while Flowchart

An example would be:

package Exercise;

public class Exercise {
    
    public static void main(String[] args)
    {
        int number = 0;
	
        while( number <= 12 )
        {
            System.out.print("Number ");
            System.out.println(number);
            number++;
        }
    }
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12
 

The do...while Statement

The do…while statement uses the following formula:

do Statement while (Condition);
 
  

The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop.

If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.

Another version of the counting program seen previously would be:

package Exercise;

public class Exercise {

    public static void main(String[] args)
    {
        int number = 0;
	
        do {
            System.out.print("Number ");
            System.out.println(number);
            number++;
        } while( number <= 12 );
    }
}

If the Statement is long and should span more than one line, start it with an opening curly bracket and end it with a closing curly bracket.

The do…while statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down.

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int sittingDown;
	String strDown;
		
	System.out.print("For the next exercise, you need to be sitting down\n");
		
	do {
            		System.out.print("Are you sitting down now(1=Yes/0=No)? ");
            		strDown = in.readLine();
            		sittingDown = Integer.parseInt(strDown);
        	} while( !(sittingDown == 1) );	
    }
}

Here is an example of running the program:

For the next exercise, you need to be sitting down
Are you sitting down now(1=Yes/0=No)? 0
Are you sitting down now(1=Yes/0=No)? 3
Are you sitting down now(1=Yes/0=No)? 8
Are you sitting down now(1=Yes/0=No)? 1

The for Statement

The for statement is typically used to count a number of recurrences. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is:

for(Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. This could be Count = 0;

The End expression sets the criteria for ending the counting. An example would be Count < 24; which means that the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting.

The Frequency expression lets the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.

Here is an example that applies the for statement:

package Exercise;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
       	 for(int count = 0; count <= 12; count++)
	{
            		System.out.print("Number ");
            		System.out.println(count);
	}
    }
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12

A variable declared as the counter of a for loop is available only in that for loop. This means that the scope of the counting variable is confined only to the for loop. This allows different for loops to use the same counter variable. Here is an example:

package Exercise;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	for(int count = 0; count <= 12; count++)
	{
            		System.out.print("Number ");
            		System.out.println(count);
	}

        	for(int count = 10; count >= 2; count--)
	{
            		System.out.print("Number ");
            		System.out.println(count);
	}
    }
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12
Number 10
Number 9
Number 8
Number 7
Number 6
Number 5
Number 4
Number 3
Number 2

Techniques of Writing Conditional Statements

 

Conditional Nesting

A condition can be created inside of another to write a more effective statement. This is referred to as nesting one condition inside of another. Almost any condition can be part of another and multiple conditions can be included inside of others.

As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role.

Here is an example of an if condition nested inside of a do...while loop:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int sittingDown;
	String strDown;
		
	System.out.print("For the next exercise, you need to be sitting down\n");
		
	do {
            		System.out.print("Are you sitting down now(1=Yes/0=No)? ");
            		strDown = in.readLine();
            		sittingDown = Integer.parseInt(strDown);
	 
            		if( sittingDown != 1 )
                		System.out.println("Could you please sit down for the next exercise? ");
        	} while( !(sittingDown == 1) );	
    }
}

Here is an example of running the program:

Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?
Are you sitting down now(y/n)? g
Could you please sit down for the next exercise?
Are you sitting down now(y/n)? y

One of the reasons you would need to nest conditions is because one would lead to another. Sometimes, before checking one condition, another primary condition would have to be met. The ergonomic program we have been simulating so far is asking the user whether she is sitting down. Once the user is sitting down, you would write an exercise she would perform. Depending on her strength, at a certain time, one user will be tired and want to stop while for the same amount of previous exercises, another user would like to continue. Before continuing with a subsequent exercise, you may want to check whether the user would like to continue. Of course, this would be easily done with:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int sittingDown;
	String strDown;
		
	System.out.print("For the next exercise, you need to be sitting down\n");
		
	do {
            		System.out.print("Are you sitting down now(1=Yes/0=No)? ");
            		strDown = in.readLine();
            		sittingDown = Integer.parseInt(strDown);
	 
            		if( sittingDown != 1 )
                		System.out.println("Could you please sit down for the next exercise? ");
        	} while( !(sittingDown == 1) );	
    }
}

If the user answers No, you can stop the program. If she answers Yes, you would need to continue the program with another exercise. Because the user answered Yes, the subsequent exercise would be included in the previous condition because it does not apply for a user who wants to stop. In this case, one “if” could be inserted inside of another. Here is an example:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int sittingDown;
	String strDown;
		
        	do {
            		System.out.print("Are you sitting down now(1=Yes/0=No)? ");
            		strDown = in.readLine();
            		sittingDown = Integer.parseInt(strDown);
		
            		if( sittingDown != 1 )
                		System.out.println("Could you please sit down for the next exercise? ");
	} while( sittingDown != 1 );

        	System.out.println("Wonderful. Now we will continue today's exercise...");
	System.out.println("\n...\nEnd of exercise\n");

        	int wantToContinue;
	
        	System.out.print("\nDo you want to continue(1=Yes/0=No)? ");
        	String strContinue = in.readLine();
	wantToContinue = Integer.parseInt(strContinue);
	
        	if(wantToContinue == '1')
	{
            	           int layOnBack;
		
 	           System.out.println("Good. For the next exercise, you should lay on your back");
 	           System.out.print("Are you laying on your back(1=Yes/0=No)? ");
	            String strLay = in.readLine();
	            layOnBack = Integer.parseInt(strLay);
		
 	           if(layOnBack == '1')
	               System.out.println("Great.\nNow we will start the next exercise.");
 	           else
	                System.out.println("\nWell, it looks like you are getting tired...");
	}
	else
            		System.out.println("We had enough today");
	
        	System.out.println("We will stop the session now\nThanks.\n");
    }
}

The break Statement

The break statement is used to stop a loop for any reason or condition the programmer considers fit. The break statement can be used in a while condition to stop an ongoing action. The formula of the break statement is simply:

break;

Although made of only one word, the break statement is a complete statement. Therefore, it can (and should always) stay on its own line (this makes the program easy to read). The break statement applies to the most previous conditional statement to it, provided that the previous statement is applicable. For example, you can use a break statement inside of a for loop to interrupt its count. The following program would display letter from d to n but it is interrupted by a break when it encounters k:

package Exercise;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        for (char c = 'd'; c <= 'n'; c++) 
       {
            if (c == 'k') 
                break;
            System.out.println(c);
        }
    }
}

This would produce:

d
e
f
g
h
i
j

The break statement can also be used in a do…while or a for loop the same way.

The break statement is typically used to handle the cases in a switch statement. Here is an example:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	int number;
	String strNumber;
	
	System.out.print("Type a number between 1 and 4: ");
	strNumber = in.readLine();
	number = Integer.parseInt(strNumber);
	
	switch(number)
	{
            	case 1:
                	System.out.print("\nYou typed 1.");
                	break;
            	case 2:
              		System.out.print("\nYou typed 2.");
                	break;
            	case 3:
               		System.out.print("\nYou typed 3.");
                	break;	
            	case 4:
               		System.out.print("\nYou typed 4.");
                	break;
            	default:
               		System.out.print("\nUnknown Option");
	}
    }
}

Here is an example of running the program:

Type a number between 1 and 4: 2

You typed 2.
 

The continue Statement

The continue statement uses the following formula:

continue;

When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, do…while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line.

The following programs asks the user to type 4 positive numbers and calculates the sum of the numbers by considering only the positive ones. If the user types a negative number, the program manages to ignore the numbers that do not fit in the specified category:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	// Declare necessary variables
	double number, sum = 0;
	String strNbr;
	
        	// Request 4 positive numbers from the user
	System.out.println("Type 4 positive numbers.");
        	// Make sure the user types 4 positive numbers
	for( int count = 1; count <= 4; count++ )
        	{
            		System.out.print("Number: ");
            		strNbr = in.readLine();
            		number = Double.parseDouble(strNbr);
		
            		// If the number typed is not positive, ignore it
            		if( number < 0 )
                		continue;
		
            		// Add each number to the sum
            		sum += number;
	}
	
        	// Display the sum
	System.out.println("Sum of the numbers you entered = " + sum);
    }
}

This would produce:

Type 4 positive numbers.
Number: 24.55
Number: 826.08
Number: 1450.85
Number: 262.58
Sum of the numbers you entered = 2564.06
 

Logical Operations on Statements

 

Introduction

The conditional statements we have used so far were applied to single situations. You can combine statements using techniques of logical operations to create more complex and complete expressions. One way to do this is by making sure that two conditions are met for the whole expression to be true. On the other hand, one or the other of two conditions can produce a true condition, as long as one of them is true. This is done with logical conjunction or disjunction.

In the beginning of the previous lesson, we described ways to write clear, simple, and logical statements. The techniques are even more important when combining statements because, once again, you should be able to make a decision based on a short, truthful, and clear statement.

Logical Conjunction: AND

One of the operations used in combining two statements consists of validating an expression made of two parts only if both parts of the statement are true. Imagine that a sport camp states on an application form that an interested candidate must be "a man at least 18 years old". This condition can be divided in two statements as follows:

  1. A - The applicant is a man
  2. B - The applicant is at least 18 years old

The program to process an application can look like this:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
	System.out.print("Age: ");
        	age = Integer.parseInt(in.readLine());
    }
}

Here is an example of running the program:

Enter the following pieces of information
Full Name: Ernestine Monay
Gender(1=Male/0=Female): 6
Age: 16

Every time a new person has filled an application, his or her information would be evaluated according to the above statements:

  • If the applicant is a man, the first statement, represented here as A would be true
  • If the applicant is 18 or older, the second statement will be rendered true.

If we evaluate these statement separately, we can tabulate them as follows:

A
 
B
 

Suppose an applicant answers the first question as being a female, but the statement on the application said that an applicant must be a male. Once this statement produces a false result. We don't care how old the applicant is, the whole statement would be false. This would produce the following table:

A B Statement
False Don't Care False

Here is an example of processing and validating the first question:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
        	if( gender == 1 )
	{
            		// If the applicant is a man, then we can continue
            		System.out.print("Age: ");
            		age = Integer.parseInt(in.readLine());
	}
        	else // If the applicant is not a man, let the applicant know
            		System.out.println("You don't qualify");
    }
}

Here is an example of running the program:

Enter the following pieces of information
Full Name: Samuel Golfer
Gender(1=Male/0=Female): 1
Age: 16

Here is another example of running the same program:

Enter the following pieces of information
Full Name: Germain Gobb
Gender(1=Male/0=Female): 6
You don't qualify

If an applicant answers the first question and indicates that he is a man, then we can process the second question. If the applicant indicates that he is younger than 18, the second statement is false. Consequently, the applicant doesn't qualify. The process this second question, we can nest a condition and change the program as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
        	if( gender == 1 )
	{
	            // If the applicant is a man, then we can continue
	            System.out.print("Age: ");
	            age = Integer.parseInt(in.readLine());
            
	            if( age < 18 )
                	System.out.println("You are not old enough!");
	}
                else // If the applicant is not a man, let the applicant know
	            System.out.println("You don't qualify");
    }
}

Here is an example of running the program:

Enter the following pieces of information
Full Name: Joseph Davis
Gender(1=Male/0=Female): 5
You don't qualify

Here is another example of running the same program:

Enter the following pieces of information
Full Name: Thomas Lemm
Gender(1=Male/0=Female): 1
Age: 16
You are not old enough!

This would produce the following table:

A B Statement
Don't Care False False

In the same way, if the applicant answers to be a female and younger than 18, the whole statement is still false. This would produce the following table:

A B Statement
False False False

As a consequence, an applicant qualifies only if he is a male and at least 18. The program that evaluates this c an be written as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
        	if( gender == 1 )
	{
	            // If the applicant is a man, then we can continue
	            System.out.print("Age: ");
	            age = Integer.parseInt(in.readLine());
            
	            if( age < 18 )
	                System.out.println("You are not old enough!");
	            else
	                System.out.println("Your application is valid");
	}
                else // If the applicant is not a man, let the applicant know
	            System.out.println("You don't qualify");
    }
}

This shows that an applicant qualifies only if both statements are true.

In the above section, to evaluate related statements, we proceeded by nesting them, which made our program complete but longer. To process this type of related statements, you can combine them using the Boolean AND operator. Based on this, a statement such as "The applicant must be a man at least 18 years old" can be segmented in two statements joined as follows:

"The applicant is a man" AND "The applicant is at least 18 years old"

In C#, the logical conjunction is performed using the && operator. A combination of A AND B can be represented as follows:

A
 
B
 
A && B
 

The expression that evaluates this combined statement can be written as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
        	System.out.print("Age: ");
        	age = Integer.parseInt(in.readLine());
        	if( gender == 1  && age >= 18 )
 	           System.out.println("Your application is valid");
        	else
	            System.out.println("You don't qualify");
    }
}

Based on the rules of operator, this logical operation will work. The compiler will evaluate the "Gender == 1" condition first, then it will evaluate the "Age >= 18" condition, then it will combine the first to the second. Sometimes this expression can appear confusing to read. If you want, you can include each part of the combination in its own parentheses. Here is an example:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int gender;
	int age;

        	System.out.println("Enter the following pieces of information");
	System.out.print("Full Name: ");
        	fullName = in.readLine();
	System.out.print("Gender(1=Male/0=Female): ");
	gender = Integer.parseInt(in.readLine());
        	System.out.print("Age: ");
        	age = Integer.parseInt(in.readLine());
        	if( (gender == 1)  && (age >= 18) )
 	           System.out.println("Your application is valid");
        	else
	            System.out.println("You don't qualify");
    }
}

This makes the program easier to read.

  • If the current applicant is a woman, our first statement, represented as A, is false
  • If the same applicant is younger than 18, our second statement, represented as B, is false
  • If both statements are false, the combined statement, represented as A&&B, or C, is false.

This can be represented in a truth table as follows:

A B A && B
False False False

Based on this table, here is an example of running the program:

Enter the following pieces of information
Full Name: Germain Asse
Gender(1=Male/0=Female): 0
Age: 16
You don't qualify
  • If the current applicant is a woman, our first statement is false
  • If the same applicant is at least 18 years old, our second statement is true
  • If the first statement is false and the second is true, the combined statement is false

This can be represented in a truth table as follows:

A B A && B
False True False

Based on this table, here is an example of running the program:

Enter the following pieces of information
Full Name: Germain Asse
Gender(1=Male/0=Female): 0
Age: 24
You don't qualify

In the same way

  • If the current applicant is a man, our first statement is true
  • If the same applicant is at least 18 years old, our second statement is false
  • If the first statement is true and the second is false, the combined statement is false

This can be represented in a truth table as follows:

A B A && B
True False False

Based on this table, here is an example of running the program:

Enter the following pieces of information
Full Name: Germain Asse
Gender(1=Male/0=Female): 1
Age: 14
You don't qualify
  • If the current applicant is a man, our first statement is true
  • If the same applicant is at least 18 years old, our second statement is true
  • If both statements are true, the combined statement is true.

This results in:

A B A && B
True True True

Based on this table, here is an example of running the program:

Enter the following pieces of information
Full Name: Germain Asse
Gender(1=Male/0=Female): 1
Age: 22
Your application is valid

The above tables can be combined into one as follows:

A B A && B
False False False
False True False
True False False
True True True

 

Logical Disjunction: OR

Imagine you are looking for a job and you come to an ad that states, "Programmer needed, an applicant should be a Microsoft Certified Application Developer (MCAD). If you are not an MCAD, you must have at least a bachelor's degree". This announcement can be resumed to the following statement: "The applicant must either be an MCAD or must have a bachelor's degree". It can be further segmented in two sub-statements as follows:

  • The applicant is an MCAD
  • The application has a bachelor's degree

The program to process an application can appear as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int MCAD;
	int degree;

	System.out.println("Enter the following pieces of information");
	System.out.print("Applicant's Name: ");
        	fullName = in.readLine();
	System.out.print("Are you an MCAD (1=Yes/0=No)? ");
	MCAD = Integer.parseInt(in.readLine());
	System.out.print("Do you hold a bachelor's degree (1=Yes/0=No)? ");
	degree = Integer.parseInt(in.readLine());
    }
}

Here is an example of running the program:

Enter the following pieces of information
Applicant's Name: Paul Brownies
Are you an MCAD (1=Yes/0=No)? 4
Do you hold a bachelor's degree (1=Yes/0=No)? 6

When a new applicant applies for a job, his or her information is evaluated:

  • If the applicant is an MCAD, the first statement, represented here as A, is true
  • If the applicant has a bachelor's degree, the second statement, represented as B, is true

If an applicant indicates in the first question that he or she is an MCAD, we wouldn't care about the second question. This resulting statement can be represented as follows:

A B Statement
True Don't Care True

Here is an example of processing and validating the first question:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int MCAD;
	int degree;

	System.out.println("Enter the following pieces of information");
	System.out.print("Applicant's Name: ");
        	fullName = in.readLine();
	System.out.print("Are you an MCAD (1=Yes/0=No)? ");
	MCAD = Integer.parseInt(in.readLine());
        	if( MCAD == 1 )
		System.out.println("Since you are an MCAD, you qualify");
    }
}

Here is an example of running the program:

Enter the following pieces of information
Applicant's Name: Saul Kemmel
Are you an MCAD (1=Yes/0=No)? 4

Here is another example of running the same program:

Enter the following pieces of information
Applicant's Name: Saul Kemmel
Are you an MCAD (1=Yes/0=No)? 1
Since you are an MCAD, you qualify

If the answer to the first question indicates that an applicant is not an MCAD, then we would be interested in the answer to the second question. If the second answers shows that the applicant has a bachelor's degree, then he or she qualifies. In fact in this case, the answer to the first question would not be important:

A B Statement
Don't Care True True

The second question can be addressed as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int MCAD;
	int degree;

	System.out.println("Enter the following pieces of information");
	System.out.print("Applicant's Name: ");
        	fullName = in.readLine();
	System.out.print("Are you an MCAD (1=Yes/0=No)? ");
	MCAD = Integer.parseInt(in.readLine());
	System.out.print("Do you hold a bachelor's degree (1=Yes/0=No)? ");
	degree = Integer.parseInt(in.readLine());
        	if( MCAD == 1 )
		System.out.println("Since you are an MCAD, you qualify");
	if( degree == 1 )
		System.out.println("Since you have the necessary degree, you qualify");
    }
}

Here is an example of running the program:

Enter the following pieces of information
Applicant's Name: Annie Baugh
Are you an MCAD (1=Yes/0=No)? 8
Do you hold a bachelor's degree (1=Yes/0=No)? 1

Since you have the necessary degree, you qualify

In the same way, if an applicant is an MCAD and holds a bachelor's degree, he or she still qualifies. This produce the following table:

A B Statement
True True True

Based on this, here is an example of running the program:

Enter the following pieces of information
Applicant's Name: Jamie Konlo
Are you an MCAD (1=Yes/0=No)? 1
Do you hold a bachelor's degree (1=Yes/0=No)? 1

Since you are an MCAD, you qualify
Since you have the necessary degree, you qualify

Therefore, if an application either is an MCAD or has a degree or fulfills both criteria, he or she qualifies. If a candidate neither is an MCAD nor has the degree, he or she cannot have the job. This can be resumed as follows:

A B Statement
False False False

Writing both statements separately can appear redundant. Instead, if you are evaluating two statements but the truthfulness of only one is enough to render both as true, you can perform a Boolean disjunction operation. This is also called an OR operator. Using this operator, our two statements can be combined as "The applicant is an MCAD" OR "The applicant has a bachelor's degree". 

In C#, the logical disjunction is performed using the || operator. A combination of A || B can be represented as follows:

A B A || B
True False True
False True True
True True True
False False False

The expression that evaluates this combined statement can be written as follows:

package Exercise;
import java.io.*;

public class Exercise {

    public static void main(String[] args) throws Exception
    {
        	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        	String fullName;
	int MCAD;
	int degree;

	System.out.println("Enter the following pieces of information");
	System.out.print("Applicant's Name: ");
        	fullName = in.readLine();
	System.out.print("Are you an MCAD (1=Yes/0=No)? ");
	MCAD = Integer.parseInt(in.readLine());
	System.out.print("Do you hold a bachelor's degree (1=Yes/0=No)? ");
	degree = Integer.parseInt(in.readLine());
        
	if( MCAD == 1 || degree == 1 )
            		System.out.println("Since you are an MCAD OR you have the necessary degree, you qualify");
	else
            	System.out.println("We will get back to you");
    }
}

Once again, based on the rules of operators precedence, the "MCAD == 1 || Degree == 1" expression will work fine. If it appears difficult to read, you can include each part in its parentheses as (MCAD == 1) || (Degree == 1).

Here is an example of running the program:

Enter the following pieces of information
Applicant's Name: Sally Kirkfield
Are you an MCAD (1=Yes/0=No)? 1
Do you hold a bachelor's degree (1=Yes/0=No)? 8

Since you are an MCAD OR you have the necessary degree, you qualify

Here is another example of running the same program:

Enter the following pieces of information
Applicant's Name: Leslie Stanislaw
Are you an MCAD (1=Yes/0=No)? 0
Do you hold a bachelor's degree (1=Yes/0=No)? 0

We will get back to you
 

Previous Copyright © 2005 FunctionX, Inc.