90 likes | 223 Vues
Math Class. AP CS 2012. Static Methods. All methods in the Math class are static. Static methods do not require the creation of an object to invoke them (use them). Static methods are invoked through the class name.
E N D
Math Class AP CS 2012
Static Methods • All methods in the Math class are static. • Static methods do not require the creation of an object to invoke them (use them). • Static methods are invoked through the class name. • When we have methods that will give the same result regardless of the object, we use static methods. We would want sqrt() method to compute the square root of the number the same every time, regardless of the individual object that may be created.
Math Methods Math.floor(3.254) Math.ceil(2.45) Math.pow(2,7) Math.abs(-9) Math.sqrt(256) Math.round(3.6) Math.max(5,7) Most Math methods return a double, but some do return integer values. We use the class name, Math, to call these methods, because they are static. = 3.0= 3.0= 128.0= 9.0= 16= 4.0= 7
//math return methods import java.lang.*; public class MathMethods { public static void main ( String[] args ) { System.out.println(Math.floor(3.254)); //= 3.0 System.out.println(Math.ceil(2.45)); //= 3.0 System.out.println(Math.pow(2,7)); //= 128.0 System.out.println(Math.abs(-9)); //= 9 System.out.println(Math.sqrt(256)); //= 16.0 System.out.println(Math.sqrt(144)); //= 12.0 System.out.println(Math.round(3.6)); //= 4 System.out.println(Math.max(5,7)); //= 7 System.out.println(Math.max(5,-7)); //= 5 System.out.println(Math.min(5,7)); //= 5 System.out.println(Math.min(5,-7)); //= -7 } } Type this intoDr. Java and run it. Change the numbers and see how it changes your output.
Random Numbers Some of the programming that is done in the real world is with games. Games must have the ability to vary or be random; thus, you must have the ability to generate random numbers. Math.random(); // returns a random number //between 0 up to, but not //including 1.
public class RandomDemo { public static void main ( String[] args ) { double dblans; int intans; dblans = Math.random() * 10; intans = (int)(Math.random() * 10); //this line needs help System.out.println("\nMath.random()"); System.out.println( dblans ); System.out.println( intans ); //why does it always output 0? } } Math.random() * 10; returns a double between 0 and 9.999999 (int) Math.random() * 10; When we typecast a double as an int, we get a number between 0 and 9 inclusively
public class RandomDemo { public static void main ( String[] args ) { double dblans; int intans; dblans = Math.random() * 10; intans = (int)(Math.random() * 10); System.out.println("\nMath.random()"); System.out.println( dblans ); System.out.println( intans ); } } How does the addition of parenthesis change this program?
Random Numbers • How can you use Math.random() to simulate rolling a die? How can we get it to return the numbers 1 – 6? (int)(Math.random()*6) + 1;