Decision Structure
Download
Report
Transcript Decision Structure
Work with Data and Decision
Structure
The eight primitive data types
Type
byte
short
int
long
Bytes
1
2
4
8
float
4
double
8
char
2
boolean
1
Use
Very short integers from -128 to 127.
Short integers from -32,768 to 32,767.
Integers from -2,147,483,648 to 2,147,483,647.
Long integers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
Single-precision, floating-point numbers from
-3.4E38 to 3.4E38 with up to 7 significant digits.
Double-precision, floating-point numbers from
-1.7E308 to 1.7E308 with up to 16 significant
digits.
A single Unicode character that’s stored in two
bytes.
A true or false value.
Note: String and Date are classes.
Slide 2
An overview of the eight primitive data types
A bit is a binary digit that can have a value of one or zero. A byte
is a group of 8 bits.
Integers are whole numbers.
Floating-point numbers provide for very large and very small
numbers that require decimal positions, but with a limited number
of significant digits.
A single-precision number provides for numbers with up to 7
significant digits. A double-precision number provides for
numbers with up to 16 significant digits.
The Unicode character set provides for over 65,000 characters
with two bytes used for each character.
The older ASCII character set provides for 256 characters with
one byte used for each character.
A boolean data type holds a true or false value.
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 3
How to initialize a variable in two statements
Syntax
type variableName;
variableName = value;
Example
int counter;
counter = 1;
Murach’s Java SE 6, C3
// declaration statement
// assignment statement
© 2007, Mike Murach & Associates, Inc.
Slide 4
How to initialize a variable in one statement
Syntax
type variableName = value;
Examples
int counter = 1;
// initialize an int variable
double price = 14.95;
// initialize a double variable
float interestRate = 8.125F;
// F indicates a floating-point value
long numberOfBytes = 20000L;
// L indicates a long integer
double distance = 3.65e+9;
// scientific notation
char letter = 'A';
// stored as a two-digit Unicode character
char letter = 65;
// integer value for a Unicode character
boolean valid = false;
// where false is a keyword
int x = 0, y = 0;
// initialize 2 variables with 1 statement
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 5
How to initialize a constant: final
Syntax
final type CONSTANT_NAME = value;
Examples
final int DAYS_IN_NOVEMBER = 30;
final double SALES_TAX = .075;
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 6
Enter Floating and Long Integer Values
To identify float values, you must type an f or F after the
number.
Example:
float taxRate=0.15F;
To identify long values, you must type an l or L after the
number.
Example:
long largeNumber = 15000L;
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 7
Arithmetic operators
Operator
+
Name
Addition
Description
Adds two operands.
-
Subtraction
Subtracts the right operand from the left.
*
Multiplication Multiplies the right and left operands.
/
Division
%
Modulus
Divides the right operand into the left. If
both are integers, the result is an integer.
Returns the remainder after a division.
++
Increment
Adds 1 to the operand (x = x + 1).
--
Decrement
Subtracts 1 from the operand (x = x - 1).
+
Positive sign
-
Murach’s Java SE 6, C3
Promotes byte, short, and char types to
the int type.
Negative sign Changes a positive value to negative, and
vice versa.
© 2007, Mike Murach & Associates, Inc.
Slide 8
Examples of simple assignment statements
int
int
int
int
int
int
int
int
int
int
x = 14;
y = 8;
result1
result2
result3
result4
result5
result6
result7
result8
double
double
double
double
double
double
double
double
double
double
Murach’s Java SE 6, C3
=
=
=
=
=
=
=
=
x + y;
x - y;
x * y;
x / y;
x % y;
-y + x;
--y;
++x;
a = 8.5;
b = 3.4;
result9 = a + b;
result10 = a - b;
result11 = a * b;
result12 = a / b;
result13 = a % b;
result14 = -a + b;
result15 = --a;
result16 = ++b;
//
//
//
//
//
//
//
//
result1
result2
result3
result4
result5
result6
result7
result8
//
//
//
//
//
//
//
//
result9 = 11.9
result10 = 5.1
result11 = 28.90
result12 = 2.5
result13 = 1.7
result14 = -5.1
result15 = 7.5
result16 = 4.4
© 2007, Mike Murach & Associates, Inc.
=
=
=
=
=
=
=
=
22
6
112
1
6
6
7
15, x = 15
Slide 9
More examples of simple assignment statements
// character arithmetic
char letter1 = 'C';
// letter1 = 'C'
char letter2 = ++letter1;
// letter2 = 'D'
Unicode integer is 67
Unicode integer is 68
How to code arithmetic expressions and
assignment statements
An arithmetic expression consists of operands and arithmetic
operators.
Binary operators operate on two operands. Unary operators
operate on just one operand.
An assignment statement consists of a variable, an equals sign,
and an expression.
When an assignment statement is executed, the value of the
expression is determined and the result is stored in the variable.
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 10
Modulus Example
• Long division:
– Quotient
– Remainder
• Enter length in inches and determine the
equivalent feet and inches:
– 57 inches = 4 feet and 9 inches
Return Smallest Number of Coins
Input: Changes in penny from 0 to 99
Output: Smallest number of coins
Examples:
26 cents: 1 Q, 1 P
57 cents: 2 Q, 1 N, 2 P
63 cents: 2 Q, 1 D, 3 P
System.out.print("enter changes between 0 to 99: ");
Scanner sc = new Scanner(System.in) ;
int Changes = sc.nextInt();
int qtr = Changes/25;
int dime = (Changes - qtr*25)/10;
int nickle = (Changes - qtr*25 - dime*10)/5;
int penny = (Changes - qtr*25-dime*10-nickle*5);
System.out.print("qtr= " + qtr + " dime=" + dime + " Nickle=" +
nickle + " penny= " + penny);
String Concatenation with the
concat method or “+”
String firstName, lastName, fullName;
System.out.println("Enter first name");
firstName=sc.next();
System.out.println("Enter last name");
lastName=sc.next();
fullName= firstName.concat(" ").concat(lastName);
// fullName=firstName + " " + lastName;
System.out.println("Full name is: " + fullName) ;
Assignment operators
Operator
=
Name
Assignment
+=
Addition
-=
*=
/=
%=
Murach’s Java SE 6, C3
Assigns to the variable…
A new value.
The result of adding the operand to the
starting value of the variable.
Subtraction
The result of subtracting the operand
from the starting value of the variable.
Multiplication The result of multiplying the operand by
the starting value of the variable.
Division
The result of dividing the operand by the
starting value of the variable.
Modulus
The value that is left over after dividing
the right operand by the value in the
variable.
© 2007, Mike Murach & Associates, Inc.
Slide 14
Statements that use the same variable on both
sides of the equals sign
count
count
total
total
price
sum =
= count + 1;
// count is increased by 1
= count – 1;
// count is decreased by 1
= total + 100.0;
// total is increased by 100.0
= total – 100.0;
// total is decreased by 100
= price * .8;
// price is multiplied by 8
sum + nextNumber;
// sum is increased by value of nextNumber
Statements that use the shortcut operators to get
the same results
count += 1;
// count is increased by 1
count -= 1;
// count is decreased by 1
total += 100.0;
// total is increased by 100.0
total -= 100.0;
// total is decreased by 100.0
price *= .8;
// price is multipled by 8
sum += nextNumber;
// sum is increased by the value of nextNumber
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 15
The order of precedence for arithmetic operations
1.
2.
3.
4.
Increment and decrement
Positive and negative
Multiplication, division, and remainder
Addition and subtraction
Example 1: A calculation that uses the default
order of precedence
double discountPercent = .2;
double price = 100;
price = price * 1 - discountPercent;
// 20% discount
// $100 price
// price = $99.8
The same calculation with parentheses that
specify the order of precedence
price = price * (1 – discountPercent);
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
// price = $80
Slide 16
Example 2: An investment calculation based on a
monthly investment and yearly interest rate
double currentValue = 5000;
// current value of investment account
double monthlyInvestment = 100;
// amount added each month
double interestRate = .12;
// yearly interest rate
currentValue = (currentValue + monthlyInvestment)
* (1 + (interestRate/12));
// currentValue = 5100 * 1.01 = 5151
Another way to calculate the current value of the
investment account
currentValue += monthlyInvestment;
// add investment
// calculate interest
double monthlyInterest = currentValue
* interestRate / 12;
currentValue += monthlyInterest;
// add interest
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 17
Example 3: Prefixed and postfixed increment
and decrement operators
int
int
int
int
a
b
y
z
=
=
=
=
5;
5;
++a;
b++;
// a = 6, y = 6
// b = 6, z = 5
How to work with the order of precedence
Unless parentheses are used, the operations in an expression take
place from left to right in the order of precedence.
To specify the sequence of operations, you can use parentheses.
When you use an increment or decrement operator as a prefix to a
variable, the variable is incremented or decremented and then the
result is assigned.
When you use an increment or decrement operator as a postfix to
a variable, the result is assigned and then the variable is
incremented or decremented.
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 18
Decision Structure
Decision: Action based on condition
Examples
• Simple condition:
– If total sales exceeds $300 then applies 5%
discount; otherwise, no discount.
• More than one condition:
• Taxable Income < =3000
• 3000 < taxable income <= 10000
• Taxable income > 10000
no tax
5% tax
15% tax
• Complex condition:
– If an applicant’s GPA > 3.0 and SAT > 1200:
admitted
Relational operators
Operator
!=
Name
Equality
Inequality
>
Greater Than
<
Less Than
>=
Greater Than Or
Equal
Less Than Or
Equal
==
<=
Murach’s Java SE 6, C2
Returns a true value if…
Both operands are equal.
The left and right operands are not
equal.
The left operand is greater than the
right operand.
The left operand is less than the
right operand.
The left operand is greater than or
equal to the right operand.
The left operand is less than or
equal to the right operand.
© 2007, Mike Murach & Associates, Inc.
Slide 21
Examples of conditional expressions
discountPercent == 2.3
// equal to a numeric
subtotal != 0
// not equal to a numeric
years > 0
// greater than a numeric
i < months
// less than a variable
subtotal >= 500
// greater than or equal to a numeric
quantity <= reorderPoint
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
literal
literal
literal
literal
Slide 22
Two methods of the String class
Method
equals(String)
equalsIgnoreCase(String)
Description
Compares the value of the String
object with a String argument and
returns a true value if they are equal.
Comparison is case-sensitive.
Works like the equals method but is
not case-sensitive.
Examples
userEntry.equals("Y")
// equal to a string literal
userEntry.equalsIgnoreCase("Y")
// equal to a string literal
(!lastName.equals("Jones"))
// not equal to a string literal
code.equalsIgnoreCase(productCode)
// equal to another string variable
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 23
The syntax of the if/else statement
if (booleanExpression) {statements}
[else if (booleanExpression) {statements}] ...
[else {statements}]
How to code if/else statements
An if/else statement, or just if statement, always contains an if
clause. It can also contain one or more else if clauses, and a final
else clause.
If a clause requires more than one statement, you enclose the
block of statements in braces. Otherwise, the braces are optional.
Any variables that are declared within a block have block scope so
they can only be used within that block.
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 24
If statements without else if or else clauses
With a single statement
if (subtotal >= 100)
discountPercent = .2;
With a block of statements
if (subtotal >= 100)
{
discountPercent = .2;
status = "Bulk rate";
}
An if statement with an else clause
if (subtotal >= 100)
discountPercent = .2;
else
discountPercent = .1;
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 25
Example: If total sales is larger than 1000,
then give 5% discount
Scanner sc = new Scanner(System.in);
double totalSales;
double discountRate=0;
System.out.println("Enter a total sales: ");
totalSales=sc.nextDouble();
if (totalSales > 1000)
discountRate=0.05;
double netPay=totalSales*(1-discountRate);
System.out.println("Net pay is: " + netPay);
double discountRate;
System.out.println("Enter a total sales: ");
totalSales=sc.nextDouble();
if (totalSales > 1000)
discountRate=0.05;
else
discountRate=0;
Even integer or odd integer
Scanner sc=new Scanner(System.in);
System.out.println("enter an integer:");
int N = sc.nextInt();
if (N % 2==0)
System.out.println("Even");
else
System.out.println("Odd");
Example: If with a block of statements
if (totalSales > 1000)
{
discountRate=0.05;
System.out.println("Thank you so much! ");
}
else
{
discountRate=0;
System.out.println("Thank you! ");
}
Variable Scope
• Block-level scope: declared within a block of code.
• Method (Procedural) level scope: declared in a
procedure
• Class-level: declared in a class but outside any
procedure.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a city name");
String City=sc.next();
if (City.equalsIgnoreCase("Paris"))
{
String Country="France";
System.out.println("It is in " + Country);
}
else
System.out.println("It is not in France");
What output you will see?
public class Main {
public static String projLevelVar="Project level";
String testVar="Class Level Var";
public static void main(String[] args) {
demoScope();
}
public static void demoScope(){
String testVar="Method Level Var";
System.out.println(testVar);
}
More than one condition
Rules for bonus:
JobCode = 1
JobCode = 2
JobCode = 3
JobCode = 4
300
500
700
1000
Scanner sc = new Scanner(System.in);
double jobCode, bonus;
System.out.println("Enter job code: ");
jobCode = sc.nextDouble();
if (jobCode==1)
bonus=300;
else if (jobCode==2)
bonus=500;
else if (jobCode==3)
bonus=700;
else
bonus=1000;
System.out.println("Bonus is: " + bonus);
An if statement with else if and else clauses
if (customerType.equals("T"))
discountPercent = .4;
else if (customerType.equals("C"))
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .2;
else
discountPercent = .1;
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 34
Case Structure with the Switch Statement
The syntax of the switch statement
switch (integerExpression)
{
case label1:
statements
break;
case label2:
statements
break;
any other case statements
default: (optional)
statements
break;
}
Murach’s Java SE 6, C4
© 2007, Mike Murach & Associates, Inc.
Slide 35
How to code switch statements
The switch statement can only be used with an expression that
evaluates to one of these integer types: char, byte, short, or int.
The case labels represent the integer values of the expression, and
these labels can be coded in any sequence.
The switch statement transfers control to the appropriate case
label.
If control isn’t transferred to one of the case labels, the optional
default label is executed.
If a case label doesn’t contain a break statement, code execution
will fall through to the next label. Otherwise, the break statement
ends the switch statement.
Murach’s Java SE 6, C4
© 2007, Mike Murach & Associates, Inc.
Slide 36
A switch statement with a default label
switch (productID)
{
case 1:
productDescription = "Hammer";
break;
case 2:
productDescription = "Box of Nails";
break;
default:
productDescription = "Product not found";
break;
}
Murach’s Java SE 6, C4
© 2007, Mike Murach & Associates, Inc.
Slide 37
Code Examle
System.out.println("enter job code:");
double jobCode=sc.nextDouble();
Switch((int) jobCode)
{
case 1:
bonus=300;
break;
case 2:
bonus=500;
break;
case 3:
bonus=700;
break;
case 4:
bonus=1000;
break;
default:
bonus=0;
break;
}
Explicit Casting
• Since the Switch structure requires an integer
expression and the jobCode is declared as a
double, we need to convert it to integer:
• From double to integer:
• int code = (int) jobCode
• From integer to double:
• int counter = 0;
• double dcounter = (double) counter;
How implicit casting works
Casting from less precise to more precise data types
byteshortintlongfloatdouble
Examples
double grade = 93;
// convert int to double
double d = 95.0;
int i = 86, j = 91;
double average = (d+i+j)/3;
// convert i and j to double values
// average = 90.666666...
Description
If you assign a less precise data type to a more precise data type,
Java automatically converts the data type. This can be referred to
as an implicit cast or a widening conversion.
Java also does implicit casting in arithmetic expressions.
Murach’s Java SE 6, C3
© 2007, Mike Murach & Associates, Inc.
Slide 40
A switch statement that falls through case labels
switch (dayOfWeek)
{
case 2:
case 3:
case 4:
case 5:
case 6:
day = "weekday";
break;
case 1:
case 7:
day = "weekend";
break;
}
Murach’s Java SE 6, C4
© 2007, Mike Murach & Associates, Inc.
Slide 41
Nested if statements
if (customerType.equals("R"))
{
// begin nested if
if (subtotal >= 100)
discountPercent = .2;
else
discountPercent = .1;
}
// end nested if
else
discountPercent = .4;
Subtota>=100?
Discount=.2
Discount=.1
Type = “R”
Or not
Discount=.4
Example
• State University calculates students tuition
based on the following rules:
– State residents:
• Total units taken <=12, tuition = 1200
• Total units taken > 12, tuition = 1200 + 200 per
additional unit.
– Non residents:
• Total units taken <= 9, tuition = 3000
• Total units taken > 9, tuition = 3000 + 500 per additional
unit.
Decision Tree
Units <=
12 or Not
Resident
or Not
Units <=
9 or Not
Consider the following code snippet.
if (aNumber >= 0)
if (aNumber == 0) System.out.println("first string");
else System.out.println("second string"); System.out.println("third
string");
Does the “else” pair with the first or the second if?
What output do you think the code will produce if
aNumber is 3?
Complex Condition
• Examples:
– A theater charges admission fee based on
customer’s age:
• 12 <= Age <= 65:
Fee = $5
• Otherwise: Fee = $3
– X University admission rules:
• If GPA > 3.5 or SAT > 1500: Admitted
– Y University admission rules:
• If GPA > 3.0 and SAT > 1200: Admitted
Logical Operators: AND, OR, NOT
• AND
• Cond1
T
T
F
F
Cond2
Cond1 AND Cond2
T
F
T
F
• OR
• Cond1
T
T
F
F
Cond2
T
F
T
F
• NOT
• Cond
T
F
NOT Cond
Cond1 OR Cond2
Examples
• Write a complex condition for: 12 <= Age <= 65
• Use a complex condition to describe age not
between 12 and 65.
• X <= 15 is equivalent to: X<15 AND X =15? (T/F)
• This complex condition is always false:
– X < 5 AND X > 10
• This complex condition is always true:
– X >= 5 OR X <= 10
Logical operators
Operator
&&
||
&
|
!
Murach’s Java SE 6, C4
Name Description
And
Returns a true value if both expressions are true.
This operator only evaluates the second
expression if necessary.
Or
Returns a true value if either expression is true.
This operator only evaluates the second
expression if necessary.
And
Returns a true value if both expressions are true.
This operator always evaluates both expressions.
Or
Returns a true value if either expression is true.
This operator always evaluates both expressions.
Not
Reverses the value of the expression.
© 2007, Mike Murach & Associates, Inc.
Slide 50
Examples of Logical Operators
1. If 12 <= Age <= 65, admission fee = 20,
otherwise, free admission
if (Age>=12 && Age <=65)
Fee=20;
else
Fee=0;
The rules to compute employee bonus are:
If JobCode = 1 or Salary < 50000, then bonus = 500
Otherwise, bonus = 1000
if (jobCode==1 || Salary<50000)
Bonus=500;
else
Bonus=1000;
Examples of logical operations
subtotal >= 250 && subtotal < 500
timeInService <=4 || timeInService >= 12
isValid == true & counter++ < years
isValid == true | counter++ < years
(subtotal >= 250 && subtotal < 500) || isValid == true
!(counter++ >= years)
How to use the logical operators
You can use the logical operators to create a Boolean expression
that combines two or more Boolean expressions.
By default, Not operations are performed first, followed by And
operations, and then Or operations.
Since the && and || operators evaluate the second expression only
if necessary, they can be referred to as short-circuit operators.
Murach’s Java SE 6, C4
© 2007, Mike Murach & Associates, Inc.
Slide 52
Example
• Electric Company charges customers based on KiloWatt-Hour
used. The rules are:
– First 100 KH,
– Each of the next 200 KH
• (up to 300 KH),
– All KH over 300,
20 cents per KH
15 cents per KH
10 cents per KH
More Complex Condition
• University admission rules: Applicants will be
admitted if meet one of the following rules:
– 1. Income >= 100,000
– 2. GPA > 2.5 AND SAT > 900
• An applicant’s Income is 150,000, GPA is 2.9
and SAT is 800. Admitted?
– Income >= 100,000 OR GPA > 2.5 AND SAT >900
• How to evaluate this complex condition?
• Scholarship: Business students with GPA at
least 3.2 and major in Accounting or CIS
qualified to apply:
– 1. GPA >= 3.2
– 2. Major in Accounting OR CIS
• Is a CIS student with GPA = 2.0 qualified?
– GPA >= 3.2 AND Major = “Acct” OR Major = “CIS”
• Is this complex condition correct?
Examples
• SAT = 800, Income 60,000, GPA 3.0, admitted?
– (SAT > 900 OR Income >= 50,000) AND Not GPA < 2.5
• A=2, B=3
– (A=3 OR NOT (B < A)) AND B=A+1
NOT
Set 1: Young: Age < 30
Set 2: Rich: Income >= 100,000
Young
Rich
Condition with Not
• University admission rules: Applicants will be
admitted if meet all the rules:
– 1. SAT > 900 OR Income >= 50,000
– 2. Not GPA < 2.5
• Condition:
– SAT > 900 OR Income >= 50,000 AND Not GPA < 2.5
– Correct?
Order of Evaluation
•
•
•
•
1. ()
2. Not
3. AND
4. OR
Examples
• SAT = 800, Income 60,000, GPA 3.0, admitted?
– (SAT > 900 OR Income >= 50,000) AND Not GPA < 2.5
• A=2, B=3
– (A=3 OR NOT (B < A)) AND B=A+1
Java Examples
• (SAT > 900 OR Income >= 50,000) AND Not GPA < 2.5
– (SAT > 900 | Income >= 50,000) & !GPA < 2.5
• GPA >= 3.2 AND (Major = “Acct” OR Major = “CIS”)
– GPA>=3.2 & (Major.equals(“Acct”) | Major.equals(“CIS”))
• (A=3 OR NOT (B < A)) AND B=A+1
– (A==3 | !(B < A)) & B=A+1
Leap Year
The complex condition to determine if a year is leap year
is:
If (the year is divisible by 4 and not divisible by 100) or (the year is divisible by
400), then it is a leap year. Write a equivalent Java complex condition.