work with data and decision structure. slide 2 note: string and date are classes

62
Work with Data and Decision Structure

Upload: robert-spencer

Post on 26-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Work with Data and Decision Structure

Slide 2

The eight primitive data types

Type Bytes Use

byte 1 Very short integers from -128 to 127.

short 2 Short integers from -32,768 to 32,767.

int 4 Integers from -2,147,483,648 to 2,147,483,647.

long 8 Long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

float 4 Single-precision, floating-point numbers from -3.4E38 to 3.4E38 with up to 7 significant digits.

double 8 Double-precision, floating-point numbers from -1.7E308 to 1.7E308 with up to 16 significant digits.

char 2 A single Unicode character that’s stored in two bytes.

boolean 1 A true or false value.

Note: String and Date are classes.

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 3

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 4

How to initialize a variable in two statements Syntax type variableName; variableName = value;

Example int counter; // declaration statement counter = 1; // assignment statement

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 5

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 6

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 7

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;

Enter Floating and Long Integer Values

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 8

Arithmetic operators

Operator Name Description

+ Addition Adds two operands.

- Subtraction Subtracts the right operand from the left.

* Multiplication Multiplies the right and left operands.

/ Division Divides the right operand into the left. If both are integers, the result is an integer.

% Modulus 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 Promotes byte, short, and char types to the int type.

- Negative sign Changes a positive value to negative, and vice versa.

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 9

Examples of simple assignment statements int x = 14; int y = 8; int result1 = x + y; // result1 = 22 int result2 = x - y; // result2 = 6 int result3 = x * y; // result3 = 112 int result4 = x / y; // result4 = 1 int result5 = x % y; // result5 = 6 int result6 = -y + x; // result6 = 6 int result7 = --y; // result7 = 7 int result8 = ++x; // result8 = 15, x = 15 double a = 8.5; double b = 3.4; double result9 = a + b; // result9 = 11.9 double result10 = a - b; // result10 = 5.1 double result11 = a * b; // result11 = 28.90 double result12 = a / b; // result12 = 2.5 double result13 = a % b; // result13 = 1.7 double result14 = -a + b; // result14 = -5.1 double result15 = --a; // result15 = 7.5 double result16 = ++b; // result16 = 4.4

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 10

More examples of simple assignment statements // character arithmetic char letter1 = 'C'; // letter1 = 'C' Unicode integer is 67 char letter2 = ++letter1; // letter2 = 'D' 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.

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 99Output: Smallest number of coins

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);

Examples:

26 cents: 1 Q, 1 P

57 cents: 2 Q, 1 N, 2 P

63 cents: 2 Q, 1 D, 3 P

String Concatenation with theconcat 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) ;

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 14

Assignment operators

Operator Name Assigns to the variable…

= Assignment A new value.

+= Addition 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.

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 15

Statements that use the same variable on both sides of the equals sign

count = count + 1; // count is increased by 1 count = count – 1; // count is decreased by 1 total = total + 100.0; // total is increased by 100.0 total = total – 100.0; // total is decreased by 100 price = price * .8; // price is multiplied by 8 sum = 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 16

The order of precedence for arithmetic operations 1. Increment and decrement

2. Positive and negative

3. Multiplication, division, and remainder

4. Addition and subtraction

Example 1: A calculation that uses the default order of precedence

double discountPercent = .2; // 20% discount double price = 100; // $100 price price = price * 1 - discountPercent; // price = $99.8

The same calculation with parentheses that specify the order of precedence

price = price * (1 – discountPercent); // price = $80

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 17

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 18

Example 3: Prefixed and postfixed increment and decrement operators

int a = 5; int b = 5; int y = ++a; // a = 6, y = 6 int z = b++; // 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.

Decision Structure

Decision: Action based on conditionExamples

• Simple condition:– If total sales exceeds $300 then applies 5%

discount; otherwise, no discount.• More than one condition:

• Taxable Income < =3000 no tax• 3000 < taxable income <= 10000 5% tax• Taxable income > 10000 15% tax

• Complex condition:– If an applicant’s GPA > 3.0 and SAT > 1200:

admitted

Murach’s Java SE 6, C2 © 2007, Mike Murach & Associates, Inc.Slide 21

Relational operators

Operator Name Returns a true value if… == Equality Both operands are equal. != Inequality The left and right operands are not

equal. > Greater Than The left operand is greater than the

right operand. < Less Than The left operand is less than the

right operand. >= Greater Than Or

Equal The left operand is greater than or equal to the right operand.

<= Less Than Or Equal

The left operand is less than or equal to the right operand.

Murach’s Java SE 6, C2 © 2007, Mike Murach & Associates, Inc.Slide 22

Examples of conditional expressions discountPercent == 2.3 // equal to a numeric literal subtotal != 0 // not equal to a numeric literal years > 0 // greater than a numeric literal i < months // less than a variable subtotal >= 500 // greater than or equal to a numeric literal quantity <= reorderPoint

Murach’s Java SE 6, C2 © 2007, Mike Murach & Associates, Inc.Slide 23

Two methods of the String class

Method Description

equals(String) Compares the value of the String object with a String argument and returns a true value if they are equal. Comparison is case-sensitive.

equalsIgnoreCase(String) 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 24

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 25

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;

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 300JobCode = 2 500JobCode = 3 700JobCode = 4 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);

Murach’s Java SE 6, C2 © 2007, Mike Murach & Associates, Inc.Slide 34

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, C4 © 2007, Mike Murach & Associates, Inc.Slide 35

The syntax of the switch statement switch (integerExpression) { case label1: statements break; case label2: statements break; any other case statements default: (optional) statements break; }

Case Structure with the Switch Statement

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 36

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 37

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; }

Code ExamleSystem.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;

Murach’s Java SE 6, C3 © 2007, Mike Murach & Associates, Inc.Slide 40

How implicit casting works Casting from less precise to more precise data types

byte short int long float double

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, C4 © 2007, Mike Murach & Associates, Inc.Slide 41

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; }

Nested if statements

if (customerType.equals("R")){ // begin nested if if (subtotal >= 100) discountPercent = .2; else discountPercent = .1;} // end nested ifelse discountPercent = .4;

Type = “R”

Or not

Discount=.2Subtota>=100?

Discount=.1

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

Resident or Not

Units <= 12 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 Cond2 Cond1 AND Cond2

T TT FF TF F

• OR• Cond1 Cond2 Cond1 OR Cond2

T TT FF TF F

• NOT• Cond NOT Cond

TF

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

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 50

Logical operators

Operator 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.

Examples of Logical Operators

if (Age>=12 && Age <=65) Fee=20; else Fee=0;

1. If 12 <= Age <= 65, admission fee = 20, otherwise, free admission

The rules to compute employee bonus are: If JobCode = 1 or Salary < 50000, then bonus = 500Otherwise, bonus = 1000

if (jobCode==1 || Salary<50000) Bonus=500;else Bonus=1000;

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 52

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.

Example• Electric Company charges customers based on KiloWatt-Hour

used. The rules are:– First 100 KH, 20 cents per KH– Each of the next 200 KH

• (up to 300 KH), 15 cents per KH– All KH over 300, 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

NOTSet 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.