+ All Categories
Home > Documents > Numeric Values and Computations Today, we extend our programming capabilities by adding numeric...

Numeric Values and Computations Today, we extend our programming capabilities by adding numeric...

Date post: 25-Dec-2015
Category:
Upload: osborne-hawkins
View: 216 times
Download: 0 times
Share this document with a friend
23
Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations As introduced last time, we can store numeric values in int and double variables int x; double y; In order to use these values, we write expressions which are much like mathematical expressions like x + 5 or y * 1.1 We store the results in other
Transcript
Page 1: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Numeric Values and Computations• Today, we extend our programming capabilities

by adding numeric values and computations– As introduced last time, we can store numeric values

in int and double variables• int x;• double y;

– In order to use these values, we write expressions which are much like mathematical expressions like x + 5 or y * 1.1

– We store the results in other variables using assignment statement

Page 2: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Assignment Statements• The assignment statement assigns a variable to a value

– variable = expression• variable is some variable previously declared • expression is some arithmetic expression using variables, literals, and

arithmetic operators +, -, *, /, % (mod)

• For an assignment statement to properly work, the expression must compute the same (or a compatible) type as the type that the variable was declared as– x = 5 * y – z; // x must be a compatible type with y and z

• Compatibility – same type or a type that can be adapted into another – an int value can become a double or float– a float can become a double– a double cannot become a float or int

Page 3: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Assignment Statement ExamplesTo compute an employee’s pay:

pay = wages * hours;

To compute the area of a circle:area = PI * radius * radius;

Or area = PI * Math.pow(radius, 2);

To compute the average of 5 test scores:average = (t1 + t2 + t3 + t4 + t5) / 5;

Note that if t1, t2, t3, t4 and t5 are int values, the expression computes an integer value (anint numerator and an int denominator cause anint division, not a float or double division)

Math is another class,we use it to peformvarious math operationslike absolute value,or exponent

Page 4: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

More on Assignments• Expressions may also contain messages to

various objects as long as the messages invoke operations that return the proper type of value– for instance, the Math class has a number of such

operations such as sqrt or abs• x = z * Math.sqrt(y); // what if y is negative?• x = z * Math.sqrt(Math.abs(y)); • x = Math.random( ); // x is a random integer value

– int values range from about -2 billion to +2 billion, this gives us a random one in that range

– or the String length message:• nameLength = firstName( ).length + middleName( ).length

+ lastName( ).length;

Page 5: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

The Modulo (Mod) Operator• A common need in a program is to perform a division

but obtain the remainder instead of the quotient– For instance, is x an even number? We determine this by

dividing x by 2 and looking at the remainder• a remainder of 0 means x is even and a remainder of 1 means x is odd

– The mod operator is %• x % 2 will be 0 or 1 (the only remainder for x / 2 is a 0 or a 1)

• Assume we want to use the random number generator to give us a roll of a 6-sided die– Math.abs(Math.random( )) % 6

• divide positive int value by 6 and provide just the remainder (0 to 5)

– Math.abs(Math.random( )) % 6 + 1 • gives us a number between 1 and 6

Page 6: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

More ExamplesVolume of a cube:

volume = length * length * length;Number of seconds in x years:

seconds = x * 365 * 24 * 60 * 60; // whats wrong with the above example?

Convert F to C:celcius = (5.0 / 9) * (fahrenheit – 32); celcius = ((double) 5) / 9 * (fahrenheit – 32);

Determining change (assume amount in cents as in 142 cents)  numQuarters = amount / 25;     //int division gives 5 quarters

 amount = amount % 25;    //remainder is 17 numDimes = amount / 10;   //gives 1 dime amount = amount % 10;    //remainder is 7 numNickels = amount / 5;   //gives 1 nickel amount = amount % 5;    //remainder is 2 pennies numPennies = amount;

Page 7: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Short Cuts• There are certain types of assignment statements that are

used so often that we given them special shortcuts– Recall earlier the “making change” example where we saw

amount = amount – numQuarters * 25;– In general, we might have a statement that looks like this:

• var = var op expression (where op is one of our arithmetic operators)– We can replace this with var op= expression

• amount –= numQuarters * 25;– The statement x = x + y * z / q;

• becomes x += y * z / q;– Another very common statement is to increment or decrement

a variable (add 1 or subtract 1)• usually, this looks like: x = x + 1; or count = count – 1;

– We replace these with x++; and count--;

Page 8: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

More on Increment/Decrement• There are two versions of each statement, a prefix

statement and a postfix statement• x = x + 1; can be done as x++; or ++x; (or x + =1;)• x = x – 1; can be done as x--; or --x; (or x -= 1;)

– x++; x--; ++x; --x;• If the incr/decr is by itself, it doesn’t matter which you

use, but these can appear inside of other expressions– x++ will use the value of x first, and then increment it

(postfix) whereas ++x will increment x first and then use the new value (prefix)

– y = 5 * x++;• this does y = 5 * x; and then does x = x + 1;• if x = 3, then when the statement is done, y = 15 and x = 4

– y = 5 * ++x; • this does x = x + 1; first and then y = 5 * x; • if x = 3, then when the statement is done, y = 20 and x = 4

Page 9: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Numeric Conversions• Two types of conversion processes in Java

– Implicit conversions (called coercions) occur automatically if the left-hand side variable is a different type as to the right-hand side expression• x = y; // y is an int, x is a double

– Casts occur because you force a value to change types• casts are performed by placing the new type in ( ) as in

(int)• average = ((double) t1 + t2 + t3 + t4 + t5) / 5;• changes t1 to a double, then the rest of the expression

computes a double value not an int value– we could force a coercion instead by doing average = (t1 + t2 + t3

+ t4 + t5) / 5.0; // 5.0 is a double, so the entire thing becomes a double

Page 10: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Converting Inputs• The JOptionPane.showInputDialog message inputs

Strings only, we have to convert the String to another form– To convert an input into an int use:

• Integer.parseInt(JOptionPane.showInputDialog(…));• int age = Integer.parseInt(JOptionPane.showInputDialog(“Enter your

age”));– To convert an input into a double use:

• Double.parseDouble(JOptionPane.showInputDialog(…));• double gpa =

double.parseDouble(JOptionPane.showInputDialog(“Enter your GPA”));

– To convert an input into a char use:• JOptionPane.showInputDialog(…).charAt(0);• char sex = JOptionPane.showInputDialog(“Enter your sex”).charAt(0);

• We prefer to use the Scanner which has next( ) for String input, nextInt( ) and nextDouble( )– For characters, we still need to use .charAt(0)

Page 11: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Control Statements• There are generally four types of executable

instructions in a program:– Assignment statements– Input/output statements– Messages (method calls)– Control statements

• In a program, all instructions are executed linearly (sequentially)– Unless a control statement alters the flow of the

program

• There are 2 types of control statements– Selection– Repetition (also called iteration or loops)

Page 12: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Branching Behavior

Sequential instructionBranching instructionSequential instructionSequential instructionBranching instructionSequential instructionSequential instructionSequential instructionBranching instructionSequential instruction…

Ordinarily, the program isexecuted by following eachsequential instruction in order

A control statement causes a “branch” to a new location

Branches may be used to selectbetween instructions, to skipover instructions, or torepeat instructions

?

Page 13: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Selection• Selection statements are used to skip an

instruction or to choose among a set of instructions

• The selection is based on a boolean evaluation– Booleans evaluate to true or false

• if true, do the statement(s), if false, skip the statement(s)• the boolean evaluation can be based on a boolean variable

or a boolean expression

– In this way, given 1 or more statements, the boolean expression is used to determine which one to select and execute

Page 14: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Boolean Expressions• A Boolean expression is code that evaluates to true or false• Boolean expressions often use relational operators to test the value

of a variable or to compare two or more variables• There are 6 relational operators:

– < less than– > greater than– = = equal to

• notice it is not the same as “=” used in assignment statements– ! = not equal to– < = less than or equal to– > = greater than or equal to

• Variables and values tested using relational operators can be of numeric types or char types, we will also see ways to compare String types

Page 15: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

The if Statement

if ( condition ) statement;

if is a Javareserved word

The condition must be a boolean expression.It must evaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

• A common form of selection statement is the if statement

• In the if statement, a condition is tested, and if it evaluates to true

then the statement which follows is executed, otherwise the statement which follows is skipped

conditionevaluated

false

statement

true

Page 16: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Examplesif (total > amount) total = total + (amount + 1);

if (sex = = ‘m’) pay = pay + 500;

if (age > 21) System.out.println("Ok, you can drink");

if (sunny) System.out.println("Wear your sunglasses!");

if (rainy) System.out.println("Take an umbrella");

if (x > y) x = x * 5 + y;

sex is a character

sunny and rainy areBoolean variables

Warning: Do not confuse = and = =

Page 17: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

A Few Comments• The statement starts with if (not IF, If or iF)• The boolean condition must be placed within ( )• The condition itself is not followed by a “;”

– For instance, the following statement would confuse the compiler into thinking that the instruction to execute for the if statement is ; and that x = y + 1; is the next instruction in the program• if (x > y); x = y + 1;

• We may couple the if statements with an “else” clause – in case there is an action to perform if the condition is false– this is known as an if-else statement (or if-then-else)

Page 18: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

if-else statement• Used if there are two possibilities– if you want to calculate

someone’s pay, there are two formulas, one for normal pay and another for overtime pay• example below to the right

• The if-else statement has two separate statements, one following the condition, one following the word else– neither the condition nor

else have a “;” after it, the “;” follows the statement• we refer to the statements as

they “if clause” and the “else clause”

conditionevaluated

statement1

true false

statement2

if (hours <= 40) pay = hours * wages;else pay = 40 * wages + (hours – 40) * wages * 1.5;

Page 19: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

More Examplesif (score > 60) grade = ‘P’;else grade = ‘F’;

if (number >= 0) sqt = Math.sqrt(number);else System.out.println("Can’t take the square root of a negative number!");

if (number = = 0) System.out.println("Can’t take reciprocal of 0");else rec = 1.0 / (float) number;

if (age >= 21) canGamble = true;else canGamble = false;

Use if-else to decide what value should be assigned a variable

Use if-else to decide if an operationcould/should be performed

Page 20: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

String Comparisons• Comparing Strings is not like comparing other values• If a and b are Strings, then this does not work: if(a = = b) …;

– This compares to see if a and b are the same thing in memory, not just two equal Strings

• To see if two String variables are storing the same values, use equals– if(a.equals(b))…; – if(a.equalsIngoreCase(b)) …; // if we don’t care about upper vs lower case

• We may want to see what the user has entered to see if they followed directions– for instance, we want the user to enter their name or quit to exit the

program• if(value.equal(“quit”)) System.exit(0);

– this only works if they type in exactly “quit”, what if they typed “Quit”?• if(value.equalIgnoreCase(“quit”)) System.exit(0);

– what if they typed “q” or “Q”?• if(value.toLowerCase( ).charAt(0) = = ‘q’) System.exit(0);

Page 21: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Another String Comparison• When it comes to sorting Strings, we will

want to know if one String is < or > than another– We use compareTo for this– compareTo returns an int value

• negative if the first String is less than the second• 0 if the first String is equal to the second• positive if the first String is greater than the second

if (a.compareTo(b) > 0)System.out.println(a + “ is greater than ” + b);

else if (a.compareTo(b) < 0) System.out.println(b + “ is greater than ” + a);

else System.out.println(a + “ is the same as ” + b);

Page 22: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Block Statements• Notice that in all of our previous examples, the

statement in the if clause and the else clause consisted of a single instruction

• What if we needed to accomplish more than one instruction in an if or else clause?– we use block statements– a block is a sequence of statements that is treated like a

single statement when placed in an if or else clause• Blocks are denoted by { } symbols

– { is the beginning of a block, } is the ending of a block• Blocks will be used often in our Java programs

Page 23: Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Example

if (temperature > 80) { System.out.print("Wear shorts and t-shirt "); effectiveTemp = temperature + HEATINDEX * humidity; System.out.println("because it is " + effectiveTemp + " degrees today"); }else System.out.println("It is not hot today, the temperature is " + temperature);

The if-clause has 3 instructions, so we place them in a block

If we didn’t use a block, then we would get a syntax error because the compiler would get confused when it reached the “else” since it did not immediately follow the if-clause


Recommended