Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
QUESTION 1:
You are driving in your car and it starts to rain. The rain falls on your windshield and makes it hard to see.
Should your windshield wipers be on or off?
Two-way Decisions
The windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is
made.
Start at the top of the chart then follow the line to the question:
is it raining?
The answer is either true or false.
If the answer is true,
o follow the line labeled True,
o perform the instructions in the box "wipers on",
o follow the line to "continue".
If the answer is false,
o follow the line labeled False,
o perform the instructions in the box "wipers off",
o follow the line to "continue".
QUESTION 2:
How many ways can you go from "start" to "continue"?
Decisions
The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems
small, but in programming, complicated decisions are made of many small decisions. Here is a program
that implements the wiper decision:
import java.util.Scanner;
class RainTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
String answer;
answer = scan.nextLine();
The if statement tests if the user entered exactly the character Y (and nothing else):
The "true branch" is separated from the "false branch" by the reserved word else.
QUESTION 3:
What happens if the user enters anything other than exactly the character Y ?
Checking a String
The if statement
if ( answer.equals("Y") )
picks either the "true branch" or the "false branch" . Only one branch or the other is executed, just as
in the flow chart. This part of the statement
answer.equals("Y")
evaluates to true if the string referenced by answer contains exactly the single character "Y" . For
anything else it evaluates to false. This is somewhat awkward. Dealing with user input is often awkward.
Later on you will see better ways to do this. Here are some runs of the program:
C:>javac RainTester.java
C:>java RainTester
Is it raining? (Y or N): Y
Wipers On
C:>java RainTester
Is it raining? (Y or N): N
Wipers Off
C:>java RainTester
Is it raining? (Y or N): Yes
Wipers Off
C:>java RainTester
Is it raining? (Y or N): Rats
Wipers Off
QUESTION 4:
Is the integer -12 negative or not?
Number Tester
An integer may be negative, or not. If it is not negative, then it is positive or zero. Here is that idea
expressed as a flow chart:
The diamond box shows a two-way decision. Either the false branch or the true branch is taken depending on
whether
num < 0
is true or false.
The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to see this in a program
where line follows line one after another. The flow chart shows the overall logic of the program. Most of the
details of syntax are left out. It is often helpful to sketch a flowchart when you are designing a program. You can
use the flowchart to get the logic correct, then fill in the details when you write the program.
QUESTION 5:
The user runs the program and enters "12". What will the program print?
The Program
Here is the number tester implemented as a program:
import java.util.Scanner;
class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;
System.out.println("Enter an integer:");
num = scan.nextInt();
if ( num < 0 )
System.out.println("The number " + num + " is negative");
else
System.out.println("The number " + num + " is zero or positive");
class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;
System.out.println("Enter an integer:");
num = scan.nextInt();
if ( num < 0 )
System.out.println("The number " +
num + " is negative");
else
System.out.println("The number " +
num + " is zero or positive"); 2. Click in the "monitor" window after the
last line and enter a number
System.out.println("Good-bye for now");
}
}
This is just a simulation (using JavaScript), so it is not exactly like a compiling and running a real Java program.
Don't take it too seriously. Please do the real thing if you can.
QUESTION 7:
Try the program (or look at the flowchart) with the value 0 (zero). What is the output?
More than one Statement per Branch
Here is the program again with some added statements:
import java.util.Scanner;
class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;
System.out.println("Enter an integer:");
num = scan.nextInt();
if ( num < 0 )
{
System.out.println("The number " + num + " is negative."); // true-branch
System.out.println("Negative numbers are less than zero."); // true-branch
}
else
{
System.out.println("The number " + num +" is zero or positive.");// false-branch
System.out.print ("Positive numbers are greater "); // false-branch
System.out.println("than zero. "); // false-branch
}
To include more than one statement in a branch, enclose the statements with braces, { and }. A group of
statements grouped together like this is called a block statement, (or usually, just block). There can be as many
statements as you want in a block. A block can go anyplace a single statement can go. All the statements in
the true block are executed when the answer to the question is true.
Of course, all the statements in the false block are executed when the answer to the question is false. The false
block consists of the block that follows the else. Notice that the very last statement in the program is not part
of the false block.
QUESTION 8:
The user enters a 17. What will the new program print?
Outline of a Two-way Decision
Here is an outline of a two-way decision structure:
// statements that are executed before the decision
if ( condition )
// true branch
else
// false branch
// statements that are executed after the branches join together again
Here are some details:
The condition evaluates to true or false, often by comparing variables and values.
The else divides the true branch from the false branch.
The statements after the false branch are always executed.
A block consists of several statements inside a pair of braces, { and }.
The true branch can be a block.
The false branch can be a block.
There can be as many statements in a block as you need.
When a block is chosen for execution, the statements in it are executed one by one.
The condition can compare what is held in a variable to other values. You can use the comparisons <, >, and
so on. (More about these later.) The first statement after the false branch will be executed no matter which branch
is chosen. The if-else is like a fork in the road, but the road always comes together again.
QUESTION 9:
Is the following section of a program correct?
if ( num < 0 )
System.out.println("The number " + num + " is negative.");
else
System.out.println("The number " + num + " is zero or positive.");
System.out.print ("Positive numbers are greater ");
System.out.println("than zero. ");
if ( num < 0 )
System.out.println("The number " + num + " is negative.");
else
System.out.println("The number " + num + " is zero or positive.");
System.out.print ("Positive numbers are greater ");
System.out.println("than zero. ");
Our human-friendly indenting shows what we want, but the compiler ignores indenting. The compiler
groups statements according to the braces. What it sees is the same as this:
if ( num < 0 )
System.out.println("The number " + num + " is negative."); // true-
branch
else
System.out.println("The number " + num + " is zero or positive"); // false-
branch
System.out.print ("Positive numbers are greater "); // always executed
System.out.println("or equal to zero. "); // always executed
System.out.println("Good-bye for now"); // always executed
QUESTION 10:
How would you fix the problem?
Practice
At a movie theater box office a person less than age 13 is charged the "child rate". Otherwise a person
is charged the "adult rate." Here is a partially complete program that does this:
import java.util.Scanner;
class BoxOffice
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int age;
if ( )
{
System.out.println("Child rate.");
}
else
{
System.out.println("Adult rate.");
}
System.out.println("Enjoy the show."); // always executed
}
}
In this program, the true branch and the false branch are both blocks. Each block contains only one statement,
but this is OK. Often programmers do this for clarity.
QUESTION 11:
Fill in the blank so that a person under the age of 13 is charged the child rate.
Box Office Program
Here is the program with the blank filled in correctly:
import java.util.Scanner;
class BoxOffice
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int age;
if ( age < 13 )
{
System.out.println("Child rate.");
}
else
{
System.out.println("Adult rate.");
}
System.out.println("Enjoy the show.");
}
}
Relational Operators
Operator Meaning
A == B is A equal to B ?
A != B is A not equal to B ?
Here are some annoying details (that will be really annoying later on if you forget about them):
The operator for "equal" is == (two equal signs in a row). In your web browser it may be hard to see
that there are two equal signs.
The operator for "not equal" is !=(exclaimation point equal sign).
It is easy to forget these two details, and easy to overlook these details in a program. You might spend hours
debugging a program because a = was used where a == belongs.
Using Boolean Expressions
In an if statement, the true or false of a boolean expression picks whether the true branch or the false branch
is executed. Look at another story problem:
A store wants a program that calculates the tax on an item of clothing. An item that costs $100 or more has a 5% tax. An
item that costs less than $100 is tax free. Write a program that asks for a price, then calculates and prints the tax, then
prints the total cost.
double price;
double tax ;
if ( )
else
Here are some program fragments to use in completing the program. Use your mouse to copy-and-paste them
into the program.
tax = price * taxRate; Scanner scan = new Scanner( System.in );
price = scan.nextDouble(); final double taxRate = 0.05;
price >= 100.0 import java.util.Scanner;
tax = 0.0;
(Of course, it would be nice to copy the program to a file, enter your corrections and run the program.)
Adding in a Zero
Here is the complete program.
import java.util.Scanner;
class TaxProgram
{
public static void main (String[] args)
{
final double taxRate = 0.05;
Scanner scan = new Scanner( System.in );
double price;
double tax ;
The flowchart shows how this works. One decision is nested inside the false branch of the first decision.
A negative integer is correctly sorted out by the first decision. But a zero or positive integer goes through
another decision to pick the correct category for it.
Number Tester Program
Here is a program that implements the flowchart. The part that corresponds to the nested decision of the flow
chart is in red. This is called a nested if statement because it is nested in a branch of an outer if statement.
import java.util.Scanner;
class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;
System.out.println("Enter an integer:");
num = scan.nextInt();
if ( num < 0 )
{
// true-branch
System.out.println("The number " + num + " is negative");
}
else
{
if ( num > 0 )
{
// nested true-branch
System.out.println("The number " + num + " is positive");
}
else
{
// nested false-branch
System.out.println("The number " + num + " is zero");
}
At the State Fair Pie Eating Contest all contestants in the heavyweight division must
weigh within 30 pounds of 250 pounds. Write a program that asks for a contestant's
weight and then says if the contestant is allowed in the contest.
Write a program that asks the user for the number of bolts, nuts, and washers in their
purchase and then calculates and prints out the total. As an added feature, the program
checks the order. A correct order must have at least as many nuts as bolts and at least
twice as many washers as blots, otherwise the order has an error. For an error the
program writes out "Check the Order: too few nuts" or "Check the Order: too few
washers" as appropriate. Both error messages are written if the order has both errors. If
there are no errors the program writes out "Order is OK." In all cases the total price in
cents (of the specified number of items) is written out.
Number of bolts: 12
Number of nuts: 8
Number of washers: 24