Lecture2 More types, methods, conditionals
1. Division
Division operates differently on integers and on doubles!!
| Java |
|---|
| double a = 5.0/2.0; // a = 2.5
int b = 4/2; // b = 2
int c = 5/2; // c = 2
double d = 5/2; // d = 2.0
|
order: precedence like math, left to right, parenthesis increase precedence
2. Mismatched Types
String five = 6 ERROR!
3. Methods
| Java |
|---|
| //adding methods
public static void NAME(){
STATEMENTS;
}
//to call a method
NAME();
//Parameters
public static void NAME(TYPE NAME){
STATEMENTS;
}
NAME(EXPRESSION);
//Multiple Parameters
[...] NAME(TYPE NAME, TYPE NAME){
STATEMENTS;
}
NAME(arg1, arg2);
//Return Values
public static TYPE NAME(){ // void means no type
STATEMENTS
return EXPRESSION
}
|
4. Variable Scope
Variables live in the block where they are defined. Method parameters are like defining a new variable in the method.
5. Building Blocks
abstraction: 拆分、封装、复用
6. Mathematical Functions
| Java |
|---|
| Math.sin(x)
Math.cod(Math.PI / 2)
Math.pow(2, 3)
Math.log(Math.log(x + y))
|
7. Conditions
| Java |
|---|
| if (CONDITION){
STATEMENTS;
}else if (CONDITION){
STATEMENTS;
}else {
STATEMENTS;
}
|
Assignments 2 FooCorporation
| Java |
|---|
| public class FooCorporation{
public static void clculatePay(int hour, double base){
if (base < 8.0) {
System.err.println("Error: base pay is lower than $8.00/hour!");
return;
}
if (hour > 60) {
System.err.println("Error: hour should lower than 60");
return;
}else if (hour <= 40) {
double pay = hour * base;
System.out.println("Total pay: $" + pay);
}else {
double pay = 40 * base + (hour - 40) * base * 1.5 ;
System.out.println("Total pay: $" + pay);
}
}
public static void main(String[] args) {
clculatePay(35, 7.5);
clculatePay(47, 8.2);
clculatePay(73, 10);
}
}
|