CS110- Lecture 4 Feb 9, 2005 Announcements

advertisement
CS110- Lecture 4
Feb 9, 2005

Announcements




Send me email (ASAP) if you don’t have
an OWL id.
Default password is “cs110”.
Lab 2 is next week.
Questions?
6/30/2016
CS110-Spring 2005, Lecture 4
1
Agenda

Expressions






Data Conversions and Conversion Techniques
Interactive Programs


Arithmetic Operators
Operator Precedence
Increment and decrement Operators
Assignment Operators
Scanner Class
Programs to Demonstrate above concepts
6/30/2016
CS110-Spring 2005, Lecture 4
2
Expressions


An Expression is a combination of one or
more operators that usually perform a
calculation.
The operands might be literals, constants
variables or other sources of data.
E.g.:
6/30/2016
int result; // declaration
result = 20/4; //Expression
result = result + 4; //Expression
CS110-Spring 2005, Lecture 4
3
Arithmetic Operators


+, - , * do what you expect them to
%(Modulus or remainder operator)
gives remainder



20 % 6 = 2
2000 % 4 (might be helpful to find if year
is a leap year)
11 % 2 (if 1 then number is odd otherwise
even)
6/30/2016
CS110-Spring 2005, Lecture 4
4
Arithmetic Operators

Division Operator (/)

Integer Arithmetic: / truncates


Decimal Arithmetic: works properly




20.0/6, 20/6.0, 20.0/6.0 are all 3.33333…
Unary Operators (only one operand)


20/6 is 3
-3, +4(rarely used)
No built in operator for exponentiation.
But Math class in java class library has methods
that perform mathematical functions.
Math.pow(2,3) = 8.0, Math.sqrt(25) = 5.0
6/30/2016
CS110-Spring 2005, Lecture 4
5
Operator Precedence




Operators can be combined to create
more complex expressions.
E.g.: result = 14 + 8/2;
The right hand expression is evaluated
and the result is stored in result
variable.
Order of operator evaluation makes a
big difference.
6/30/2016
CS110-Spring 2005, Lecture 4
6
Operator Precedence

All expressions are evaluated according to an
operator precedence hierarchy.



result
18
However precedence can be forced by using
parentheses.


E.g.: result = 14 + 8/2;
E.g.: result = (14 + 8)/2;
result
11
Parentheses can be nested and the innermost
nested expressions are evaluated first.
E.g.: result = 3 * ((18-4) /2 ); result 21
6/30/2016
CS110-Spring 2005, Lecture 4
7
Operator Precedence



+, -, *, /, % : Left to right associative –
meaning that arithmetic operators at the
same level of precedence are performed left
to right.
+ and - have same precedence
*, /, % have same precedence (higher than +
and -)

E.g.: result = 3 * (18-4)/2 ;
result
21

E.g.: result = 3 + 16 /4 - 2 ;
result
5
6/30/2016
CS110-Spring 2005, Lecture 4
8
Operator Precedence


A syntactically correct expression has
matching left and right parentheses.
When a variable is referenced in an
expression, its current value is used to
perform the calculation.

E.g.: int count = 4, total = 5, sum;
sum = count + total; sum 9
sum = sum + 1;
sum
10
6/30/2016
CS110-Spring 2005, Lecture 4
9
Increment and Decrement
operators

Increment operator (++) adds 1 to the
value and decrement operator (--) subtracts
from the value

sum++;
// this will increment value of sum by 1 and result is
// stored back into the variable sum


sum++ (postfix increment operator)
++sum (prefix increment operator)
6/30/2016
CS110-Spring 2005, Lecture 4
10
Increment and Decrement
operators


sum++ and ++sum are functionally
equivalent.
When these operators are used in a larger
expression they can yield different results.
If sum is 15 then


total = sum++; //total is 15 and sum is 16
total = ++sum; //total is 16 and sum is 16
6/30/2016
CS110-Spring 2005, Lecture 4
11
Assignment Operators

+= can be used as follows
sum += 5;
// sum = sum +5;
 // following statement is equivalent to
// sum = sum+total+12/count
sum += total + 12/count ;

Likewise we can use -=, *=, /=, %=
6/30/2016
CS110-Spring 2005, Lecture 4
12
Data Conversion




It is sometimes helpful and necessary to convert
data value of one type to another type.
Careful about losing information.
Suppose a variable of type long is converted to
int value (narrowing conversion)- Loss of
information.
Suppose a variable of type int is converted to
long value (widening conversion)- Generally no
loss of information as more storage space
available.
6/30/2016
CS110-Spring 2005, Lecture 4
13
Conversion Techniques
Assignment Conversion
long money = 24567890987L;
int dollar = 342567;
money = dollar; //int value is converted
// to long variable
If we try to do
dollar = money; //compile time error
But we can do this by: dollar = (int) money; //Casting

6/30/2016
CS110-Spring 2005, Lecture 4
14
Conversion Techniques

Promotion- This conversion occurs
automatically when certain operators need
to modify their operands in order to perform
the operation.

float sum = 25.0F;
int count = 3;
float result = sum /count;//count is promoted
// to float automatically
String totalStudents= “Total:”+ 24;
6/30/2016
CS110-Spring 2005, Lecture 4
15
Conversion Techniques



Casting- The most general form of
conversion in Java. A cast is a java
operator that is specified by a type name
in parenthesis.
dollar = (int) money; //Casting
int total = 10;
int count = 4;
float result = total /count; //result = 2.0
float result = (float) total /count; //2.5
6/30/2016
CS110-Spring 2005, Lecture 4
16
Interactive programs



Good programs read data from the user
interactively during execution.
This way new results can be computed
each time the program is run.
The Scanner class which is part of the
standard Java class library(1.5) provide
convenient methods for reading input
values of various types.
6/30/2016
CS110-Spring 2005, Lecture 4
17
Scanner class



Before sending requests to (or calling
methods of) any class we must create its
instance (object).
Mostly use new reserved word to create a
new object.
Note that String is an exceptional case:
String greeting = “Hello! World”;
String greeting = new String (“Hello! World”);
6/30/2016
CS110-Spring 2005, Lecture 4
18
Scanner class


Scanner keyboard = new Scanner(System.in);
Message invoking a method

int i = keyboard.nextInt()
nextInt()
{
get number user types
i = that number
return that number
}
Somewhere in Scanner.java
6/30/2016
CS110-Spring 2005, Lecture 4
19
Add two numbers
public class SumTwoNumbers
{
//Execution always starts from main
public static void main(String[] args)
{
System.out.println(“Enter two numbers on line”);
Scanner keyboard = new Scanner(System.in);
int num1 = keyboard.nextInt();
int num2 = keyboard.nextInt();
System.out.println(“Sum is:”);
System.out.println(num1+num2);
}
}
6/30/2016
CS110-Spring 2005, Lecture 4
20
More programs….




Write a class AppleBasket.
It should have only one method main.
It asks the user for no. of baskets and no. of apples
in each basket. It then prints the total no. of apples.
Output should be something like this:
Enter the number of apples in each basket:
6
Enter the number of baskets:
10
The total number of apples is: 60
6/30/2016
CS110-Spring 2005, Lecture 4
21
More programs….




Write a class ChangeMaker.
It should have only one method main.
It asks the user for a no. between 1 and 99. It tells
the user one combination of coins that equals that
amount of change.
Output should be something like this:
Enter a number between 1 and 99:
87
87 cents in coins can be given as:
3 quarters
1 dimes
0 nickels
2 pennies
6/30/2016
CS110-Spring 2005, Lecture 4
22
Pseudo code for ChangeMaker
1.
2.
3.
4.
5.
6.
7.
8.
Declare originalAmount, amount, quarters, dimes,
nickels, pennies of type int
Read the amount from user into the variable amount
Assign amount to originalAmount
Set the variable quarters equal to the maximum
number of quarters in amount.
Reset amount to the change left after giving that
many quarters.
Repeat steps 4 and 5 for dimes and nickels.
Assign amount left to pennies
Output originalAmount and the numbers of each coin.
6/30/2016
CS110-Spring 2005, Lecture 4
23
Exercise

Programming Projects



2.2
2.8
Reading Exercise

Section 2.7 – 2.9
6/30/2016
CS110-Spring 2005, Lecture 4
24
Download