Laboratory 6

Decisions, Decisions

Note: You will need the new version of the Scanner.class file

Objective

As your knowledge of the Java language grows, your capacity to write more useful and more complex programs also increases. The if statement is a powerful tool for decision making. However, it can lead to considerable confusion if you do not fully understand its usage. This laboratory familiarizes you with the if statement, Boolean logic, and introduces you to program decision making.

Key Concepts

·         The if statement

·         Boolean logic

·         Truth tables

·         Comparing objects using equals()

7.1              getting Started

·         Using the procedures in the previous laboratories, copy the files IsSorted.java, IsReverse.java, IsTriangle.java, Nand.java, Mystery.java, Stringy.java, and Predict.java for your manipulation.

 

7.1              Syntax Errors aren't the only problem

In addition to syntax errors, also known as compile-time errors, there are also logic errors. Code often compiles successfully (i.e., there are no syntax errors). Does this mean that the code will work? Well, it will do exactly what you tell it to do, but not necessarily what you want it to do.

Programmers sometimes write programs that they think look correct and that compile without producing any errors, but do not produce the intended results (i.e., there are logic errors). This situation results in frustrated users, and sometimes in users who do not know that the program is producing incorrect results.

One source of logic errors is misunderstandings about the uses of particular language features and their effects on the flow of execution in the program (what the program does and which paths it takes when you run it).

In the following exercises you will learn how to follow the logic of an if statement and to create tests cases to show that are there are no logic errors.

7.2              Checking ORDER

The if statement allows the programmer to make decisions. If some expression is true, one course of action is taken. If the expression is false, the course of action is skipped. The if statement can lead to problems. The following exercises will help you to understand the if statement so that you can avoid some of its troublesome pitfalls.

·         Open the program IsSorted.java. This program checks whether its user supplies three numbers in nondecreasing order. If they are not in nondecreasing order, a message is displayed and the program immediately terminates using the Java method System.exit(). Otherwise, the program does not produce any output. The program accomplishes its task through a single if statement.

import java.util.*;

 

public class IsSorted {

 

   public static void main(String[] args) {

 

      // prompt for and extract three numbers in nondecreasing order

 

      Scanner stdin = new Scanner(System.in);

 

      System.out.println("Enter three numbers in nondecreasing order; ");

      System.out.println("i.e., first <= second <= third.\n");

 

      System.out.print("First number: ");

      int value1 = stdin.nextInt();

 

      System.out.print("Second number: ");

      int value2 = stdin.nextInt();

 

      System.out.print("Third number: ");

      int value3 = stdin.nextInt();

 

      // make sure user followed the rules

 

      if ( (value1 > value2) || (value2 > value3) ) {

         // the user did not follow the instructions – print message and exit

 

         System.out.println("Unacceptable values. Program exits.");

         System.exit(0);

      }

   }

}

 

·         Examine the program and record what you expect as the result of supplying as input, the values 5, 4, and 8 (in that order). Re-examine the program and record what you expect as the result of supplying as input, the values 4, 5, and 8 (in that order). Record your answers.

·         Compile and run the program to check your understanding. Compare its results with what you had expected. If they differ, examine the code more carefully to see what is happening. If you cannot reconcile the differences, discuss them with an instructor.

·         Why do you think it is important to develop a set of test inputs so that every part of a program is executed at least once? This question is a great exam question. Knowing the answer is important.

·         Close IsSorted.java.

·         Open the file IsReverse.java. The purpose of this program is to determine whether its inputs are in non-increasing order. Complete the program. As part of the program include comments that list test cases that together ensure all of the code is tested.

·         Submit IsReverse.java.

·         Close the file.

7.3              Checking triangleness

·         Open the program IsTriangle.java. This program begins in a similar manner as program IsSorted.java. However, it asks for three positive nondecreasing numbers. After extracting the inputs, the program checks as did IsSorted.java whether the three numbers are in nondecreasing order. If they are not in nondecreasing order, a message is displayed and the program immediately terminates using the Java method System.exit().

·         If the input values pass the ordering test, the program checks whether they are possible lengths of the sides of a triangle. For the values to represent the lengths of a triangle, the sum of the first two input values must be greater than the length of the third value. In other words, the values do not represent a triangle if the sum of the first two values is less than or equal to the third value.

import java.util.*;

 

public class IsTriangle {

 

   public static void main(String[] args) {

 

      // prompt for and extract three positive numbers in nondecreasing order

 

      Scanner stdin = new Scanner(System.in);

 

      System.out.println("Enter three numbers in nondecreasing order; ");

      System.out.println("i.e., first <= second <= third.\n");

 

      System.out.print("First number: ");

      int value1 = stdin.nextInt();

 

      System.out.print("Second number: ");

      int value2 = stdin.nextInt();

 

      System.out.print("Third number: ");

      int value3 = stdin.nextInt();

 

      // make sure user followed the rules

 

      if ( (value1 > value2) || (value2 > value3) ) {

         // the user did not follow the instructions – print message and exit

 

         System.out.println("Unacceptable values. Program quits.");

         System.exit(0);

      }

 

      // user followed the instructions, now test whether inputs form

      // triangle sides

 

      if ( (value1 + value2) <= value3 ) {

         // lengths do not form a triangle

 

         System.out.println("Lengths do not represent triangle sides.");

      }

      else {

         // lengths form a triangle

 

                System.out.println("Lengths represent triangle sides.");

      }

   }

}

·         Examine program IsTriangle.java and record what you expect as the result of supplying as input, the values 5, 4, and 8 (in that order). Re-examine the program and record what you expect as the result of supplying as input, the values 4, 5, and 8 (in that order). Record your answers.

·         Compile and run the program to check your understanding. Compare its results with what you had expected. If they differ, examine the code more carefully to see what is happening. If you cannot reconcile the differences, discuss them with an instructor.

·         Our test cases do make sure that all lines of code within the program are executed. But is the program correct? Does it verify that the input is of the specified form? Consider the inputs -4, 0, and 1 (in that order). What output should the program display? What output does the program display? The program needs to be modified to accomplish its task in a truly correct manner – an error message should be displayed if the numbers are not of the requested form. To implement the modification, the program needs to perform an additional check regarding the input. This new check must determine whether the inputs are positive. If the other check has already been made, then testing whether the smallest value (value1) is greater than zero tells us whether the inputs are all positive.

·         There are several ways to add the check. One possibility is to expand the Boolean expression that tests the program to see whether this other condition is also met. The advantage to this approach is that the code is short. However, is the code still simple to read? Another possibility is a separate if statement that follows the first if statement. Other possibilities also exist.

·         Modify IsTriangle.java using one of the two listed possibilities mentioned above.

·         Retest the program using all three of our test cases. Whenever changes are made to a program. It should be completely retested. You need to be sure that a correction has not introduced a new error.

·         If your modified program is incorrect, examine it line-by-line to determine how the errant output was produced.

·         Once a correct program has been developed, submit it.

·         Close the file.

7.4              BEING CONTRARY

You will now use the if statement to help compute the value of a standard Boolean operation.

·         Open the file Nand.java.

import java.util.*;

 

public class Nand {

   public static void main(String[] args) {

 

      // Prompt user and read input values for p and q

 

 Scanner stdin = new Scanner(System.in);

 

 

      System.out.print("Please enter a logical value (true, false): ");

      boolean p = stdin.nextBoolean();

 

      System.out.print("Please enter another logical value (true, false): ");

      boolean q = stdin.nextBoolean();

 

      // compute the correct value to assign to nand using if-else-if's

 

      boolean nand;

      if ( (!p) && (!q) ) {

         nand = true;

      }

      else if ( (!p) && (q) ) {

         nand = true;

      }

      else if ( (p) && (!q) ) {

         nand = true;

      }

      else {  // (p) and (q)

         nand = false;

      }

      // display nand's value

 

      System.out.println( p + " nand " + q + " = " + nand);

   }

}

 

·         This program offers one solution to the following truth table for the Boolean nand operation, which is the negation of the and operation (not (p and q)).

p

q

nand

false

false

true

false

true

true

true

false

true

true

true

false

 

·         Using the four possible input combinations, run the program to verify its correctness.

·         Observe that only the final combination—p and q both true—causes the nand result to be false. Restructure your code so that it uses a single if and else to achieve the same functionality. (Test only whether the combination defined in the last row of the truth table is the one you have).

·         Compile and run the program. Once it is correct, submit it. If you cannot determine the proper test expression, ask for help.

·         Close the file.

7.5              A Common Mistake

 

·         Consider the following program Mystery.java. What is its output? Record your guess.

public class Mystery {

 

   public static void main(String[] args) {

      boolean b = false;

 

      if (b = false) {

         System.out.println("b is false");

      }

      else {

         System.out.println("b is true");

      }

   }

}

·         Open the file Mystery.java and then compile and run it. Is the output, the same as your guess?

·         Many people when reading the program do not notice that an = was used rather than an ==. A single = is the assignment operator (i.e., it’s not the equality operator). The value of an assignment operation is the value assigned to the variable. For this assignment, the value is false. Therefore, the test expression is false and the else action is executed.

·         Correct the program so that an equality test is made. Compile and run the program.

·         Once the program is correct submit it.

·         The purpose of this exercise is to encourage you to pay strict attention when developing test expressions. Make sure the expression is what you want!

·         Close the file.

7.6              Comparing objects

·         Open the program Stringy.java. The purpose of this program is to test whether the user has provided identical inputs.

import java.util.*;

 

public class Stringy {

   public static void main(String[] args) {

 

      // Prompt user and read input strings for input1 and input2

 

 Scanner stdin = new Scanner(System.in);

 

 

      System.out.print("Please enter some text: ");

      String input1 = stdin.nextLine();

 

      System.out.print("Please enter more text: ");

      String input2 = stdin.nextLine();

 

      // test whether input1 and input2 have the same value

 

      if ( input1 == input2 ) {

         System.out.println(input1 + " equals " + input2);

      }

      else {

         System.out.println(input1 + " differs from " + input2);

      }

   }

}

·         Compile and run the program using as input the strings “facetious” and “subbookkeeper”. Does the program work as you expected?

·         Run the program using “strengths” and “strengths” as inputs. Does the program work as you expected?

·         Many beginning programmers forget that the == operator tests whether two variables have the same value. In particular for reference variables, it tests whether the variable refer to the same object. This test was not the test the program was supposed to perform. Rather the program was supposed to test whether equivalent character strings representations are being referenced by variables input1 and input2.

·         To test whether two String objects represent equivalent character strings representations, String method equals() should be used. Open the Java API at javasoft.com to read about method equals (). Modify the program to use method equals().

·         Compile and run your program. If you are having difficulty, ask your lab instructor for assistance.

·         Enter several different test cases to ensure that your program is working correctly.

·         Submit the completed program.

·         Close the file.

7.7              A Simple Prediction

·         Examine the following program Predict.java. Determine what inputs are needed for the string “1” to be displayed, what inputs are needed for the string “2” to be displayed, and so for strings “3”, “4”, and “5”.

import java.util.*;

 

public class Predict {

 

   public static void main(String[] args) {

 Scanner stdin = new Scanner(System.in);

 

      System.out.print("Enter a logical value (true or false):");

      boolean p = stdin.nextBoolean();

 

      System.out.print("Enter a logical value (true or false):");

      boolean q = stdin.nextBoolean();

 

      System.out.print("Enter a logical value (true or false):");

      boolean r = stdin.nextBoolean();

 

      if (p && q) {

         if (r) {

            System.out.println("1");

         }

         else {

            System.out.println("2");

         }

      }

      else if (q && r) {

            System.out.println("3");

         }

         else {

            if (p || !r) {

               System.out.println("4");

            }

            else {

               System.out.println("5");

            }

         }

 

   }

}

 

·         Record your answers in the handout. Show two ways for “4” to be displayed. Are there others? Give the completed handout to the lab instructor.  101-E students: put the answers in the Predict.java file as a comment.

·         Close the file.

7.8              Finishing up

·         Copy any files you wish to keep to your own drive.

·         Delete all of the files you copied or created on the laboratory machine.