Lesson 6- Input and Output: Working With Math Formulas
Learning Goals:
- To know about some of the more common math formulas provided by Java
- To know about some math constants in Java
- To be able to translate a formula from math into a formula in Java code
- To introduce the student to the concept of input.
The math library
In this lesson, you will be making use of the math library. In the first line of code you need an import statement, namely: import java.lang.Math
There are a number of math functions that are part of the math library. A few key functions are:
| Function Name |
Purpose /notes |
| math.pow(p, q) |
Returns pq (floating point) |
| math.trunc(p) |
Where p is floating point, it returns the integer part (decimal is discarded) |
| math.floor(p) |
Where p is floating point, it rounds to the next lowest integer |
| math.ceil(p) |
Where p is floating point,it rounds to the next higher integer |
| math.sqrt(p) |
Returns the square root of p (floating point) |
What follows are some useful stored constants in Python. Use them in place of numbers. Constants do not make use of brackets and are treated like variables.
| Constant |
Value |
| math.PI |
3.141592653589793 (the value of π) |
| math.e |
2.718281828459045 (the value of Euler's constant) |
| math.inf |
Positive infinity, ∞ |
What to do:
- Predict. Look at the code below in the green box. In your reflection, predict what output you would expect from the statement.
import java.lang.Math;
import java.util.Scanner; # import commands always go at the top
Scanner sc = new Scanner(System.in); # how input functions are declared
System.out.print("Please input a length: ");
int length = sc.nextInt(); # scans for an integer and assigns it
double area = pow(length, 2)
System.out.println("The area of a square of side length", length, "is:", area);
- Run. Run the code in NetBeans, to check your response.
- Inspect. State the behaviour of this code. When it stopped execution, why did it stop? What did you input? Did the output match what you did on your calculator?
- Modify/Make. This time, compute the area of a square with a semicircle on one side, in the shape of a Norman Window. The area of the semicircle is 0.5*πr2; while the area of the square can be (2r)2=4r2. The total area is the sum of these: 0.5*πr2 + 4r2. In your reflection, state the reason why r has to be multiplied by 2 in part of the formula. In the diagram below, x = y.
Sample session:
Area of a Norman Window shape
Input the circle's radius: 5
Area is: 139.26990816987242