Information Technology Reference
In-Depth Information
Table 8.2 Lab-first worksheet (This worksheet was developed by Dr. Tamar Paz and is
included here with her permission. See Paz ( 2006 , pp. 33-36))
Worksheet
The Conditional Statement If
Conditional statements enable to write computer programs that act in one way if a given condition is
fulfilled, and to act differently if the condition is not fulfilled.
import java.util.Scanner;
public class Condition {
public static Scanner input = new
Scanner(System.in);
public static void main(String[] args) {
double num;
System.out.println(“enter number”);
num = input.nextDouble();
System.out.println(“good number”);
System.out.println(“end”);
Task 1, Part A
Open a new class and type the class presented on
the left.
Save it, run it, check its output and write it down.
}
}
import java.util.Scanner;
public class Condition {
public static Scanner input = new
Scanner(System.in);
public static void main(String[] args) {
double num;
System.out.println(“enter number”);
num = input.nextDouble();
if (num > 0)
System.out.println(“good number”);
System.out.println(“end”);
Task 1, Part B
We now change the class so that the message “good
number”is printed only if the variable num is
positive.
Change the class according to thecode on the left.
Save it and run it.
When the program waits for an input, type a
positive number.
The output is: ___________________
Run it again. This time, when theprogram waits for
an input, type a negative number.
The output is: ___________________
}
}
Complete the following sentence:
The meaning of the statement
if (num > 0)
System.out.println(“good number”);
is: if ______________________________________
then ___________________________________
The general structure of the conditional statement if is:
if (a condition to be checked)
a statement for execution;
Task 2, Part A
Write a program that prints "Good" for a given grade if it is higher than 80.
Save it and run it several times. Each time type a different grade and verify that the message is printed only
when the grade is higher than 80. Try also the number 80.
Task 2, Part B
Add to your program a conditional statement so that if the grade is lower than 55, theprogram prints the
message “Try Again”.
Save and run it several times. Each time type a different grade and check that the correct message is
printed.
import java.util.Scanner;
public class License {
public static Scanner input = new
Scanner(System.in);
public static void main(String[] args) {
double age;
System.out.println(“enter age”);
age = input.nextDouble();
if (age>=17)
Task 3, Part A
The class on the left includes an operation that
declares whether a driver license can be
obtained for a given age.
Type the class.
Save it and run it three times. Each time, type a
different age and fill in the following table:
 
Search WWH ::




Custom Search