Lecture6-2024
Lecture6-2024
SCIENCE
CSI141
PROGRAMMING
h t t p s : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l PRINCIPLES
Programming Principles T ALLMAN NKGAU
L ECTURE 6 – F UNDAMENTAL
D ATA TYPES
‣ Java Functions
‣ The Java Math Library
‣ Reading numbers from the
keyboard
https://horstmann.com/bjlo/index.html
L EARNING OUTCOMES
to:
a Java function
h t t p s : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
Java Function
5
Java Function
Formal parameters
Type of value returned
Function name
❑ x and y are used to hold values passed to
the function. Two integers must be
passed/given to the function average .
int a = 55;
double avg = average(45, a);
❑ The function average returns a value, a
double value (a real number).
6
‣ Functions
‣ The Java Math Library
‣ Reading numbers from the
keyboard
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l
Java Library – Java Math Library
❑ A Java class
▪
With static methods – functions
➢ Tested, efficient, and made available to be used by
others
Name of function
Formal parameters Purpose of function
A double value
is returned
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Math.html
Page 9
Powers and Roots
In Java, there are no symbols for powers and
roots
– Becomes:
b * Math.pow(1 + r / 100, n)
Page 11
POP QUIZ
Assume x = 17, y = 15 and that x, y, z are int
variables, while w and t are double variables.
b) (−𝑏 + 𝑏 2 − 4𝑎𝑐)/2𝑎
c) tan(5𝑥)
Page 12
Example – with Math functions
}
}
𝝅 𝑉 = 𝜋r ℎ 2
‣ Functions
‣ The Java Math Library
‣ Reading numbers from the
keyboard
h t t p s : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
Reading input
This is a three-step process in Java
15
Other reading methods
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Scanner.html
16
Exercise
17
Solution – analysis and design
19
Solution – the program
// prompt for radius and read it
System.out.printf(“Enter radius: “); // prompt
radius = in.nextDouble(); // read a double
// processing
volume = Math.PI * radius * radius * height;
// output
System.out.printf(“Volume = %.2f\n”, volume);
}
}
20
Summary
Page 21
Exercises
1. E2.3 – E2.8
2. P2.3
3. P2.7
Page 22