Random - NYU Computer Science Department

Download Report

Transcript Random - NYU Computer Science Department

Math class methods
&
User defined methods
Math class methods
Math.sqrt(4.0)
Math.random()
• java.lang is the library/package that provides Math
class methods such as
– Math.random() to generate random numbers
• Java.lang is accessed by all java programs by
default.
– YOU do not have to include it at the beginning of the
program as you do with javax package.
3
Random-Number Generation
• Often we want our programs to generate random
numbers.
– games of chance
– testing without user interaction
• Java random-number generators
– Math.random()
• Returns a double value with a positive sign, greater than
or equal to 0.0 and less than 1.0.
– What if we want to generate random integers?
 2000 Prentice Hall, Inc. All rights reserved.
4
Random-Number Generation
– Math.random()
• Produces double
• from
0.0 to 1.0 (excluding 1)
• ( int ) ( Math.random() * 6 )
• Produces integers from
0–5
Scaling
– 1 + ( int ) ( Math.random() * 6 )
• Produces integers from
Shifting
 2000 Prentice Hall, Inc. All rights reserved.
1–6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
5
// Fig. 6.7: RandomIntegers.java
// Shifted, scaled random integers.
import javax.swing.JOptionPane;
Outline
public class RandomIntegers {
public static void main( String args[] )
{
int value;
String output = "";
Produce integers in range 1-6
// loop 20 times
for ( int counter = 1; counter <= 20; counter++ )
{
// pick random integer between 1 and 6
value = 1 + ( int ) ( Math.random() * 6 );
output += value + "
";
// append value to output
// if counter divisible by 5, append newline to String output
if ( counter % 5 == 0 )
Math.random returns doubles. We cast the
double as an int
output += "\n";
} // end for
 2000 Prentice Hall, Inc. All rights reserved.
6
26
27
28
29
30
31
32
33
34
JOptionPane.showMessageDialog( null, output,
"20 Random Numbers from 1 to 6",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class RandomIntegers
RandomIntegers.java
 2000 Prentice Hall, Inc. All rights reserved.
Outline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 6.8: RollDie.java
// Roll a six-sided die 6000 times.
import javax.swing.*;
7
Outline
public class RollDie {
Produce integers in range 1-6
public static void main( String args[] )
{
int frequency1 = 0, frequency2 = 0, frequency3 = 0,
frequency4 = 0, frequency5 = 0, frequency6 = 0, face;
String output;
// summarize results
for ( int roll = 1; roll <= 6000; roll++ ) {
face = 1 + ( int ) ( Math.random() * 6 );
// determine roll value and increment appropriate counter
switch ( face ) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
 2000 Prentice Hall, Inc. All rights reserved.
Increment appropriate frequency counter,
depending on randomly generated number
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
} // end switch
} // end for
Output = "Face\tFrequency" + "\n1\t" + frequency1 +
"\n2\t" + frequency2 + "\n3\t" + frequency3 +
"\n4\t" + frequency4 + "\n5\t" + frequency5 +
"\n6\t" + frequency6 ;
JOptionPane.showMessageDialog( null, output,
"Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class RollDie
 2000 Prentice Hall, Inc. All rights reserved.
8
Outline
9
 2000 Prentice Hall, Inc. All rights reserved.
Benefits of Methods




Experience has shown that the best way to develop
and maintain large programs is to build it from
smaller components or modules.
In Java, one such module is the method.
Each module is generally simpler and more
manageable than the entire program.
This concept is known as Divide and Conquer,
also with Abstraction in the mix.
11
User defined Method returning a value
• General format of method declaration:
Method header
modifiers return-value-type method-name( parameter1, …, parameterN )
{
Method body
Scope of local
variables
declarations
and statements
}
• Method can return one value:
return expression;
• Or, it can returns nothing using keyword void
in the header.
 2000 Prentice Hall, Inc. All rights reserved.
Return Value Types
• You can only return one value from a method.
• Returning void
– void: means nothing
– A method that returns void therefore returns nothing.
– Hence, there is no need for the optional return statement. But
using one can force early exit from the method.
– Example:
public static void printIntro (int n);
Parameter Data Types
• Unlike return values, you can pass as many
parameters as you like.
• To pass more than one parameter, you need to
separate the parameters with commas.
public static int maximum (int x, int y)
{
/*body*/
}
Warning
• Unlike declaring variables, you must specifically
state the type for multiple variables
– For example
takeInTwoFloats( float x, y )
is incorrect
– Instead you must write
takeInTwoFloats(float x, float y)
No parameters
• You can also have a method that accepts no
parameters. In such case, you would just have an
empty parameter list.
E.g.
public static int rollDie ()
public static void printIntro ()
16
6.5
Argument Promotion
• Coercion of arguments
– Forcing arguments to appropriate type to pass to method
• e.g., System.out.println( Math.sqrt( 4 ) );
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
• Promotion rules
– Specify how to convert types without data loss
 2000 Prentice Hall, Inc. All rights reserved.
17
Type
double
float
long
int
char
short
byte
boolean
Valid promotions
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double
short, int, long, float or double
None (boolean values are not considered to be
numbers in Java)
Fig. 6.5 Allowed promotions for primitive types.
 2000 Prentice Hall, Inc. All rights reserved.
Lets write a program in class to convert
temperatures
– Use two methods to write a program that prints charts
showing the Fahrenheit equivalent of all Celsius
temperatures from 0 to 100 degrees
– and the Celsius equivalents of all Fahrenheit temperatures
from 32 to 212 degrees.
– Print the output in a neat tabular format.
• Use the following methods:
– Method Celsius returns the Celsius equivalent of a
Fahrenheit temperature (( 5.0 / 9.0 * ( fTemp - 32 ) )
– Method Fahrenheit returns the Fehrenheit equivalent of a
Celsius temperature ( 9.0 / 5.0 * cTemp + 32 )
 2000 Prentice Hall, Inc. All rights reserved.
review
• What is a method?
• What information can you learn about a method
from its header?
• What does it mean to invoke a method?
• What is call by value?
• What is scope of local variables within a method?
• Why don’t we have to import the Math class?
• What is abstraction in computer science?