IT 114: Introduction to Java
Class 13
Topics
Review
New Material
Homework 5
Homework 5 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Review
Converting Strings to Integers
- The args parameter in the main
lets a Java program use command line arguments
- But command line arguments are strings
- If () wanted to convert the String variable input
into an integer I would write
Integer.parseInt(input);
Control Structures
- When a program runs, its statements are executed in a particular order
- This order is called the
flow of control
- Or the path of execution
- The usually the order in which statements are executed is simple
- Start at the top and execute every statement
- Until the bottom is reached
- Control structures
are features of a computer languages that allow for a different order of execution
- There are two types of control structures
- Loops
- Conditionals or Branches
Conditionals or Branches
- Conditional control structures are like switches on a railroad track
- Which path the train takes depends on how the switch is set
- When the
java
interpreter comes across a conditional
statement it has to make a decision
- It has to decide what statements to execute next
- Usually it makes this decision by evaluating an expression whose only possible values are true and false
- There are four conditionals in Java
- But for the moment we will only consider three
- The
if
statement
- The
if
/else
statement
- The
if
/else if
statement
The boolean
Data Type
- A variable of type
boolean
can only have the values true or false
- The name comes from the British mathematician George Boole who invented this field of mathematics
- A boolean expression
is an expression whose only possible values are true and false
- There are two boolean literals
Relational Operators
if
Statements
if
/else
Statements
Nested if
Statements
if
statements are
compound statements
- That means they can have statements inside them
- An
if
statement is a statement
- So you can have an
if
statement inside an if
statement
- Just like you can have a
for
statement inside a for
statement
- This called a nested if statement
if
/ else if
Statements
New Material
Relational Operator Precedence
- Relational operators can often appear in complex expressions
- Consider the following expression
3 + 2 * 2 == 9
- Which operation is carried out first?
- To evaluate expression like this Java uses its rules of precedence
- We have run across this before
- But we need to see where the relational operators stand in the precedence scheme of things
- Here is a more complete listing of operator precedence
Description | Operators |
Unary operators | ++ -- |
Multiplicative operators | * / % |
Additive operators | + - |
Relational operators | < > <= >= |
Equality operators | == != |
- To evaluate the expression below we look for operator with the highest precedence
3 + 2 * 2 == 9
- That operator is multiplication, so
3 + 2 * 2 == 9
becomes
3 + 4 == 9
- The operator with the next highest precedence is addition, so
3 + 4 == 9
becomes
7 == 9
- This expression only has one operator, == and it evaluates to false
- Relational operators have one major limitation
- They can only be used with
primitive data types
- They can't be used to compare
objects
- Later we'll discuss how to test for equality between objects
Taking the Square Root of a Number
- What if we wanted to take the square root of a number?
- How would we do this in Java
- To get the square root of 2 in Java we would write
Math.sqrt(2)
- Here is a program to calculate the square roots of the numbers from 1 to 10
public class SquareRoot {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
System.out.println("The square root of " + num + " is " + Math.sqrt(num));
}
}
}
- We we run it we get
$ java SquareRoot
The square root of 1 is 1.0
The square root of 2 is 1.4142135623730951
The square root of 3 is 1.7320508075688772
The square root of 4 is 2.0
The square root of 5 is 2.23606797749979
The square root of 6 is 2.449489742783178
The square root of 7 is 2.6457513110645907
The square root of 8 is 2.8284271247461903
The square root of 9 is 3.0
The square root of 10 is 3.1622776601683795
Other Mathematical Methods in Math
- Math contains many other useful mathematical methods
- Here is a partial list
Method | What it does |
Math.abs() | Absolute value |
Math.max() | The greater of two numbers |
Math.min() | The lesses of two numbers |
Math.sqrt() | Square root |
Math.cbrt() | Cube root |
Math.random() | A random number between 0.0 and 1.0 |
Math.log() | Natural logarithm |
Math.log10() | Base 10 logarithm |
Math.cos() | Cosine |
Math.sin() | Sine |
Math.tan() | Tangent |
- Here is a program that uses these methods
public class MathFunctions {
public static void main (String[] args){
System.out.println("Math.abs(-6) " + Math.abs(-6));
System.out.println("Math.max(5,-6) " + Math.max(5,-6));
System.out.println("Math.min(5,-6) " + Math.min(5,-6));
System.out.println("Math.sqrt(5) " + Math.sqrt(5));
System.out.println("Math.cbrt(5) " + Math.cbrt(5));
}
}
- When we run this we get
$ java MathFunctions
Math.abs(-6) 6
Math.max(5,-6) 5
Math.min(5,-6) -6
Math.sqrt(5) 2.23606797749979
Math.cbrt(5) 1.709975946676697
Math Constants
- In addition to math methods, Math also contains constants
Constant | What it is |
Math.PI | π - The ratio of the circumference of a circle to its diameter |
Math.E | e - The base of the natural logarithms |
- Here is a program that uses these constants
public class MathConstants {
public static void main (String[] args){
System.out.println("Math.PI: " + Math.PI);
System.out.println("Math.E: " + Math.E);
}
}
- When we run this we get
$ java MathConstants
Math.PI: 3.141592653589793
Math.E: 2.718281828459045
Creating Random Numbers
- Many things in nature are random
- The number of dust particles in a room
- Whether a coin comes up heads or tails
- The number of leaves in my yard
- The number of water droplets in a cloud
- Random events are things that cannot be exactly predicted
- In other word, events with no patterns
- When writing programs, we often need random numbers
- We need them in writing
- Would a game of solitaire be any fun if the cards always appeared in the same order?
- Simulations are extremely important in many sciences
- Astronomers use simulations to study the evolution of galaxies
- Climate scientists use simulations to see what global warming will bring
- For both games and simulations we need random numbers
- But we have a problem
- Nothing that a computer does is random
- If you give a program the same input .you will always get the same output
- In other words, the output of a program is completely determined
- There is nothing random about it
- But the need for random numbers in computing is very great
- So mathematicians have developed algorithms that create
pseudorandom numbers
- These algorithms create a sequence of numbers
- In a truly random sequence, the numbers would never repeat
- In a pseudorandom sequence the numbers eventually repeat
- But the interval between repeats is so long that they are "random" enough for most purposes
- The methods that create these pseudorandom sequences are called
pseudorandom number generators
- Sometimes they are simply called random number generators, although that term in not really accurate
Using Math.random()
- Math contains the method random
- Every time you call this method you get a different number from 0.0 to 1.0
- Here is an example
public class Random {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
System.out.println(Math.random());
}
}
}
$ java Random
0.42701409808126933
0.4293017265566993
0.9773529013623884
0.3209691412511697
0.951876469610539
0.7713989339985787
0.3478186972710844
0.22613552068080456
0.6832152019141671
0.22463007958908288
- But what if you wanted a number in a different range?
- If we needed a number from 0.0 to 10.0 we multiply the the result of calling
Math.random() by 10
public class Random2 {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
System.out.println(Math.random() * 10);
}
}
}
$ java Random2
5.5097666718175065
7.168880302236071
0.9126412436509579
3.467208698076024
5.715109474349978
6.491510685795239
1.4792639289303389
6.6375111397252216
2.9590730299740775
5.847767928650263
- What if instead we wanted a number from 1.0 to 5.0/
- This requires a little more thought
- We could add 1 to
Math.random() * 5
- But this would give us number between 1.0 and 6.0
- To get the range we want we need to multiply by 1 less than 5
public class Random3 {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
System.out.println(Math.random() * 4 + 1);
}
}
}
$ java Random3
2.5606368088971347
1.2012779853245288
4.718764489758655
2.516798719694851
3.9464697054984463
4.265437262845495
4.050599817171813
4.9945555060439055
2.720716039876587
1.2510095026653105
Casting
- Java is a strongly typed language
- Scripting languages like Python are flexible about data types
- But Java is not
- Python recognizes different data types
- But it has methods that will turn one data type into another
- Java uses a different approach
- You can force a variable of one data type to behave like another by
using a cast
- It uses the following format
(DATA_TYPE) EXPRESSION
- So if the variable num was a
double
but I needed an int
I would write
(int) num
Creating Random Integers
- Let's create a method to return random integers within a certain range
- The method header will look like this
public static int rand_int(int max, int min)
- We can get a random number between max
and min with the following statement
double value = Math.random() * (max - min) + min;
- We can then cast value to
int
and return it
return (int) value;
- Here is a program containing rand_int
and a loop to demonstrate it
public class RandInt {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
System.out.println(rand_int(10, 1));
}
}
public static int rand_int(int max, int min){
double value = Math.random() * (max - min) + min;
return (int) value;
}
}
- Running this we get
$ java RandInt
2
3
5
1
1
1
4
5
2
7
A Game of Dice
- One of the principle uses of random numbers is in games
- Let's write a program to emulate such a game
- Each die has six sides with 1 through 6 dots on each side
- Each player roles the dice by throwing two dice on a flat surface
- You then total the value on the two dice
- Here is a program that simulates this
public class Dice {
public static void main (String[] args){
for (int num = 1; num <= 10; num++){
roll();
}
}
public static void roll(){
int die_1 = rand_int(7, 1);
int die_2 = rand_int(7, 1);
System.out.println(die_1 + " and " + die_2 + " adds up to " + (die_1 + die_2));
}
public static int rand_int(int max, int min){
double value = Math.random() * (max - min) + min;
return (int) value;
}
}
- Running this we get
$ java Dice
4 and 3 adds up to 7
5 and 5 adds up to 10
2 and 3 adds up to 5
3 and 5 adds up to 8
2 and 4 adds up to 6
3 and 4 adds up to 7
3 and 2 adds up to 5
3 and 5 adds up to 8
5 and 4 adds up to 9
1 and 2 adds up to 3
- Why use
(die_1 + die_2)
instead of
die_1 + die_2
- Because the second expression will concatenate the two integer values
- Not add them
- That would give a result like this
2 and 4 adds up to 24
5 and 2 adds up to 52
1 and 3 adds up to 13
2 and 2 adds up to 22
...
Using One Program to Build Another
- The program Dice.java was created by making a copy
of RandInt.java
- Then the roll method was added
- And the main method modified to call roll
- Programs are often built this way
- It saves time, because you can use code that already works
- In a future class we will show you how to create a class filled with useful methods
- You can then use this class inside other programs
Class Quiz
Attendance
Class Exercise