COMPSCI 121: DATA TYPES & BRANCHING
FALL 19
BYTE FROM COMPUTING HISTORY
Alan Turing, also known as the father of
modern computing was a brilliant
mathematician and logician. He
developed the idea of the modern
computer and artificial intelligence.
Read about the Turing Machine.
2
GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• New data types
• Conditional branching
• Math methods and operators
3
LET’S DO SOME REVIEW
Website Java Visualizer:
https://cscircles.cemc.uwaterloo.ca/java_visualize/
Look at Basic Examples:
4
CLICKER QUESTION #1
REVIEW COMPOUND OPERATORS
What is the value of numCalories after executing
numCalories = 7;
numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5;
D. Same as numCalories = 7 + 5;
5
CLICKER QUESTION #1 ANSWER
6
zyBooks 2.6 Shorthand way to update a variable.
E.g. userAge++ or userAge += 1 is shorthand for
userAge = userAge + 1
Others -=, *=, /=, and %=.
What is the value of numCalories after executing
numCalories = 7; numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5; incorrect
D. Same as numCalories = 7 + 5;
CLICKER # 2 REVIEW: INSTANTIATING CLASS
Select the statement below that declares a variable named myCalculator
and assigns to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator;
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;
D. myCalculator = new SalaryCalculator(); 7
CLICKER # 2 ANSWER
Select the statement below that declares a variable named myCalculator and assigns
to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator; declares but does not assigns
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;missing ()
D. myCalculator = new SalaryCalculator();missing class type 8
CLICKER QUESTION #3 REVIEW METHOD CALLS
9
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6
B. 12
C. 0
D. 18
CLICKER QUESTION #3 ANSWER
10
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6 size of cheese pizza
B. 12 correct
C. 0 incorrect answer
D. 18 incorrect answer
EXPLANATION CLICKER QUESTION #3
There are 2 constructors.
public Pizza(int size){...}
public Pizza(int size, String type){...}
11
DATA TYPES IN JAVA
• Data is represented as “types” in programming.
• In Java, a data type is defined as a primitive or a class.
• “Primitive” Data types and their values:
•Numeric: int, whole numbers, 2, 400, -99
double, fractional numbers, 7.34, 8.01,
-100.00
•Character: char, alpha-numeric symbols, ‘a’, ‘G’, ‘&’ , ‘}’, ‘9’
(notice 9 is not a number but character 9).
•Boolean: boolean, true or false (these values are
keywords). 12
RELATIONAL OPERATORS
Check conditions: Result of boolean type: true or false
13
Two sides of a
relational operator
have to be
compatible types.
Note:
==
!=
CONDITIONAL IF-ELSE
14
if (<some boolean test>)
do something;
if (<some boolean test>)
   { do a bunch of things;}
if (<some boolean test>)
   {do a bunch of things;}
else
{do a bunch of other things;}
If no curly braces, only the first line after the if statement is executed.
<
>
<=
>=
Relational operators
Boolean evaluates to
TRUE / FALSE
CONDITIONALS - STYLE 1
15
if (x > 0) {
   System.out.println("x is positive");
}
else if (x < 0) {
   System.out.println("x is negative");
}
else {
   System.out.println("x is zero");
}
What is the answer if x = -2? See Demo from Java Visualizer:
ControlFlow
16
if (x == 0) {
   System.out.println("x is zero");
}
else {
   if (x > 0) {
      System.out.println("x is positive");
   }
   else {
      System.out.println("x is negative");
   }
}
CONDITIONALS - STYLE 2
USE OF CONDITIONALS
17
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer");
int number = scan.nextInt();
if (number < 0)
   System.out.println("Number entered isn't positive");
if (number > 0)
   System.out.println(number + " is positive");
else
   System.out.println(number + " is negative or zero");
Use conditionals for
user error checks!
A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
CLICKER QUESTION #4
18
int x = 5;
if (x > 0){
   System.out.println("x is positive");
}
System.out.println("x is not zero");
What is printed?
A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
int x = 5;
if (x > 0)
   {System.out.println("x is positive")};
System.out.println("x is not zero");
CLICKER QUESTION # 4 ANSWER
19
{Scope of if statement}
20
• +, -, * behave in standard way.
• Division / is different
• In the absence of parentheses,
*, /, have higher precedence than +, -
• So: (3 + 5 * 2)is 13
(7 - 4 / 2) is 5
JAVA ARITHMETIC OPERATORS
5/3
1
5.0/3
1.6666666666666667
5/3.0
1.6666666666666667
See Demo from Java Visualizer:
CmdLineArgs
21
Modulo mod operator %
With integers:
Gives integer remainder after repeated divisions of the
number by the modulus:
number % modulus
10 % 7 is 3
21 % 7 is 0
53 % 7 is 4
JAVA ARITHMETIC OPERATORS
22
1. * / % have higher priority and performed first.
2. For same priority, operators are applied from left to
right.
3. Integer division always rounds towards zero.
4. When one or more operands are double, Java
performs “floating-point” division.
Check the Java™ Tutorials:
https://docs.oracle.com/javase/tutorial/java/nutsandb
olts/datatypes.html
KEEP IN MIND
MATH OPERATOR RULES
• Dividing by zero gives error
Exception in thread "main"
java.lang.ArithmeticException: / by zero
• int-to-double conversion is automatic but
double-to-int conversion may lose precision.
• Use type casting to convert a value of one type to another
type. e.g.
myIntVar = (int)myDoubleVar
myDoubleVar = (double)myIntVar
23
CLICKER QUESTION # 5
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
24
CLICKER QUESTION #ANSWER
NOTE:
JAVA converts from int
to double automatically
so 5.0 assigned to
num2.
25
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
MATH METHODS - EXAMPLE
https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html 26
Static method: Independent of class object
REVIEW: METHODS AND PARAMETERS
Parameters refers to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method
is invoked.
When you invoke a method, the arguments used must match the
declaration's parameters in type and order. 27
double r = Math.max(3.5, 7.1);
ArgumentsReturn
From the
Java API,
Math class
max method
summary.Parameters
MATH METHOD EXAMPLES
28
double r = Math.max(3.5, 7.1); //7.1
double s = Math.sqrt(2.0);
//1.4142135623730951
double t = Math.sin(.7); //0.644217687237691
double u = Math.min(3.5, 7.1); //3.5
double v = Math.pow(2,5); //32.0
JGRASP DEBUGGER - TRY WITH LECTURE CODE
Arithmeticx.java
29
STRATEGIES FOR DEBUGGING
1. Set a breakpoint prior to the line of code where you
think the problem occurs.
2. When the program gets to the breakpoint, inspect the
variables for correct values.
3. Correct the error and repeat till the program runs
correctly.
30
TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
31
COMPSCI 121: DATA TYPES & BRANCHING
FALL 19
GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• Review conditional statements
• The Random method
• Characters & Strings
2
REVIEW: CONDITIONAL IF STATEMENTS
First evaluate (alpha > beta):
(2 > 1) TRUE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is TRUE so we
execute the true branch:
eta = alpha + 2 = 2 + 2 = 4
gamma = alpha + 5 = 2 + 5 = 7
3
int alpha = 2, beta = 1,
delta = 3, eta = 0, gamma = 0;
Think - Pair -Share
4
int alpha = 2;
int beta = 1,
int delta = 3,
int eta = 0,
int gamma = 0;
Evaluate these
statements and
determine the value of all
variables used.
EXPLANATION
For if statement, determine whether
true or false
First we evaluate (alpha > delta):
(2 > 3) FALSE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is FALSE so we follow
the else branch.
gamma = beta + 5 = 1 + 5 = 6
Next sequential statement is always
executed:
eta = beta + 2 = 1 + 2 = 3
5
CLICKER QUESTION 1
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2; 6
Evaluate the statements and
determine the value of eta
given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa
= 3.0;
A. 2
B. 3
C. 4
D. 5
CLICKER QUESTION 1 ANSWER
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2;
7
Evaluate the statements and
determine the value of eta given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa =
3.0;
A. 2
B. 3
C. 4
D. 5
FALSE
TRUE
To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns a random
number
8
call nextInt()
method
Import statement
New instance
To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns 10 possible values from 0 to 9 9
10
OTHER USES OF nextInt METHOD
Generates any 6 values starting at 10.
11
OTHER USES OF nextInt METHOD
With a specific seed, each program run will yield the same
sequence of pseudo-random numbers.
Set the seed
declare int variable
CLICKER QUESTION #2
Which of the following will work like flipping a coin
and getting us 0 and 1 (heads/tail)?
A. randGen.nextInt(0);
B. randGen.nextInt(1);
C. randGen.nextInt(2);
D. randGen.nextInt(3);
12
CLICKER QUESTION #2 ANSWER
Which of the following will work like flipping a coin?
A. randGen.nextInt(0);
Error: bound must be positive
B. randGen.nextInt(1);
Gives 0;
C. randGen.nextInt(2);
Gives 0/1 (heads/tails)
D. randGen.nextInt(3);
Gives 0, 1, or 2 13
CHARACTER DATA TYPE
14
String References 1INTRODUCTION TO REFERENCES
String greeting = new
String("hi");
String greeting2 = new
String("hello");
greeting = greeting2;
“hi"
:String
greeting
“hello"
:String
greeting2
greeting
:String
“hello"
:String
greeting2
15
REFERENCES WITH STRING LITERALS
String greeting = "bonjour";
String greeting2 = "bonjour";
“bonjour"
:String
greeting greeting2
16
IDENTITY vs EQUALITY (STRINGS)
== tests identity
input1==input2
false!
== is not true here (different objects)
"bye"
:String
"bye"
:String
input1
== ?
input2
String input1 = new String(”bye");
String input2 = new String(”bye");
17
IDENTITY VS EQUALITY (STRINGS)
equals tests equalityinput1.equals(input2)
TRUE!
Only use "==" to test if whole numbers or characters
are equal. For String use the method equals
"bye"
:String
input1
"bye"
:String
equals ?
input2
18
EQUALITY OPERATORS: SUMMARY
Checks whether two operands' values are the same
(==) or different (!=).
Evaluates to a Boolean value: TRUE or FALSE.
Also useful for checking expressions e.g.
19
CLICKER QUESTION #3
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
20
CLICKER QUESTION #3 ANSWER
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
Evaluate:
name1.equals(
name2)
Ans: TRUE
21
Scanner console = new Scanner(System.in);
Scanner object means: input from keyboard
console.nextInt()--- looking for int value
console.nextDouble()--- looking for double value
console.next() --- looking for String value
console.nextLine() --- looking for a whole line
https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html
REVIEW: SCANNER CLASS METHODS
22
CLICKER QUESTION #4
A. String phrase = sc.nextInt();
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase;
D. String phrase = sc.nextLine;
E. String phrase = sc.nextString();
Scanner sc = new Scanner(System.in);    
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
23
CLICKER QUESTION #4ANSWER
A. String phrase = sc.nextInt(); For ints
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase; No such method
D. String phrase = sc.nextLine; Missing ()
E. String phrase = sc.nextString(); No such
method
Scanner sc = new Scanner(System.in);    
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
24
TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
• Read ALL the exam instructions sent to
you.
25

Week 4

  • 1.
    COMPSCI 121: DATATYPES & BRANCHING FALL 19
  • 2.
    BYTE FROM COMPUTINGHISTORY Alan Turing, also known as the father of modern computing was a brilliant mathematician and logician. He developed the idea of the modern computer and artificial intelligence. Read about the Turing Machine. 2
  • 3.
    GOALS FOR TODAY’SCLASS You are now familiar with Objects and Classes and writing programs to solve a problem. We now work with the “building blocks” or syntax of the Java programming language: • New data types • Conditional branching • Math methods and operators 3
  • 4.
    LET’S DO SOMEREVIEW Website Java Visualizer: https://cscircles.cemc.uwaterloo.ca/java_visualize/ Look at Basic Examples: 4
  • 5.
    CLICKER QUESTION #1 REVIEWCOMPOUND OPERATORS What is the value of numCalories after executing numCalories = 7; numCalories += 5; Select the incorrect answer A. Same as numCalories = numCalories + 5; B. Same as numCalories = 12; C. Same as numCalories = 5; D. Same as numCalories = 7 + 5; 5
  • 6.
    CLICKER QUESTION #1ANSWER 6 zyBooks 2.6 Shorthand way to update a variable. E.g. userAge++ or userAge += 1 is shorthand for userAge = userAge + 1 Others -=, *=, /=, and %=. What is the value of numCalories after executing numCalories = 7; numCalories += 5; Select the incorrect answer A. Same as numCalories = numCalories + 5; B. Same as numCalories = 12; C. Same as numCalories = 5; incorrect D. Same as numCalories = 7 + 5;
  • 7.
    CLICKER # 2REVIEW: INSTANTIATING CLASS Select the statement below that declares a variable named myCalculator and assigns to it a new object of type SalaryCalculator. A. SalaryCalculator myCalculator; B. SalaryCalculator myCalculator = new SalaryCalculator(); C. SalaryCalculator = new SalaryCalculator; D. myCalculator = new SalaryCalculator(); 7
  • 8.
    CLICKER # 2ANSWER Select the statement below that declares a variable named myCalculator and assigns to it a new object of type SalaryCalculator. A. SalaryCalculator myCalculator; declares but does not assigns B. SalaryCalculator myCalculator = new SalaryCalculator(); C. SalaryCalculator = new SalaryCalculator;missing () D. myCalculator = new SalaryCalculator();missing class type 8
  • 9.
    CLICKER QUESTION #3REVIEW METHOD CALLS 9 If the program prints 6 when line 6 is executed, what would the following statement print? System.out.println(yourTopping.getSize()); A. 6 B. 12 C. 0 D. 18
  • 10.
    CLICKER QUESTION #3ANSWER 10 If the program prints 6 when line 6 is executed, what would the following statement print? System.out.println(yourTopping.getSize()); A. 6 size of cheese pizza B. 12 correct C. 0 incorrect answer D. 18 incorrect answer
  • 11.
    EXPLANATION CLICKER QUESTION#3 There are 2 constructors. public Pizza(int size){...} public Pizza(int size, String type){...} 11
  • 12.
    DATA TYPES INJAVA • Data is represented as “types” in programming. • In Java, a data type is defined as a primitive or a class. • “Primitive” Data types and their values: •Numeric: int, whole numbers, 2, 400, -99 double, fractional numbers, 7.34, 8.01, -100.00 •Character: char, alpha-numeric symbols, ‘a’, ‘G’, ‘&’ , ‘}’, ‘9’ (notice 9 is not a number but character 9). •Boolean: boolean, true or false (these values are keywords). 12
  • 13.
    RELATIONAL OPERATORS Check conditions:Result of boolean type: true or false 13 Two sides of a relational operator have to be compatible types. Note: == !=
  • 14.
    CONDITIONAL IF-ELSE 14 if (<someboolean test>) do something; if (<some boolean test>)    { do a bunch of things;} if (<some boolean test>)    {do a bunch of things;} else {do a bunch of other things;} If no curly braces, only the first line after the if statement is executed. < > <= >= Relational operators Boolean evaluates to TRUE / FALSE
  • 15.
    CONDITIONALS - STYLE1 15 if (x > 0) {    System.out.println("x is positive"); } else if (x < 0) {    System.out.println("x is negative"); } else {    System.out.println("x is zero"); } What is the answer if x = -2? See Demo from Java Visualizer: ControlFlow
  • 16.
    16 if (x ==0) {    System.out.println("x is zero"); } else {    if (x > 0) {       System.out.println("x is positive");    }    else {       System.out.println("x is negative");    } } CONDITIONALS - STYLE 2
  • 17.
    USE OF CONDITIONALS 17 Scannerscan = new Scanner(System.in); System.out.println("Enter a positive integer"); int number = scan.nextInt(); if (number < 0)    System.out.println("Number entered isn't positive"); if (number > 0)    System.out.println(number + " is positive"); else    System.out.println(number + " is negative or zero"); Use conditionals for user error checks!
  • 18.
    A. x ispositive B. x is not zero C. x is positive x is not zero D. Error CLICKER QUESTION #4 18 int x = 5; if (x > 0){    System.out.println("x is positive"); } System.out.println("x is not zero"); What is printed?
  • 19.
    A. x ispositive B. x is not zero C. x is positive x is not zero D. Error int x = 5; if (x > 0)    {System.out.println("x is positive")}; System.out.println("x is not zero"); CLICKER QUESTION # 4 ANSWER 19 {Scope of if statement}
  • 20.
    20 • +, -,* behave in standard way. • Division / is different • In the absence of parentheses, *, /, have higher precedence than +, - • So: (3 + 5 * 2)is 13 (7 - 4 / 2) is 5 JAVA ARITHMETIC OPERATORS 5/3 1 5.0/3 1.6666666666666667 5/3.0 1.6666666666666667 See Demo from Java Visualizer: CmdLineArgs
  • 21.
    21 Modulo mod operator% With integers: Gives integer remainder after repeated divisions of the number by the modulus: number % modulus 10 % 7 is 3 21 % 7 is 0 53 % 7 is 4 JAVA ARITHMETIC OPERATORS
  • 22.
    22 1. * /% have higher priority and performed first. 2. For same priority, operators are applied from left to right. 3. Integer division always rounds towards zero. 4. When one or more operands are double, Java performs “floating-point” division. Check the Java™ Tutorials: https://docs.oracle.com/javase/tutorial/java/nutsandb olts/datatypes.html KEEP IN MIND
  • 23.
    MATH OPERATOR RULES •Dividing by zero gives error Exception in thread "main" java.lang.ArithmeticException: / by zero • int-to-double conversion is automatic but double-to-int conversion may lose precision. • Use type casting to convert a value of one type to another type. e.g. myIntVar = (int)myDoubleVar myDoubleVar = (double)myIntVar 23
  • 24.
    CLICKER QUESTION #5 int num1 = 5.1; double num2 = 5; What are the values? A. num1 has value 5.1; num2 has value 5 B. num1 has value 5; num2 has value 5.0 C. num1 has value 5; num2 has value 5 D. Error: incompatible types 24
  • 25.
    CLICKER QUESTION #ANSWER NOTE: JAVAconverts from int to double automatically so 5.0 assigned to num2. 25 int num1 = 5.1; double num2 = 5; What are the values? A. num1 has value 5.1; num2 has value 5 B. num1 has value 5; num2 has value 5.0 C. num1 has value 5; num2 has value 5 D. Error: incompatible types
  • 26.
    MATH METHODS -EXAMPLE https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html 26 Static method: Independent of class object
  • 27.
    REVIEW: METHODS ANDPARAMETERS Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order. 27 double r = Math.max(3.5, 7.1); ArgumentsReturn From the Java API, Math class max method summary.Parameters
  • 28.
    MATH METHOD EXAMPLES 28 doubler = Math.max(3.5, 7.1); //7.1 double s = Math.sqrt(2.0); //1.4142135623730951 double t = Math.sin(.7); //0.644217687237691 double u = Math.min(3.5, 7.1); //3.5 double v = Math.pow(2,5); //32.0
  • 29.
    JGRASP DEBUGGER -TRY WITH LECTURE CODE Arithmeticx.java 29
  • 30.
    STRATEGIES FOR DEBUGGING 1.Set a breakpoint prior to the line of code where you think the problem occurs. 2. When the program gets to the breakpoint, inspect the variables for correct values. 3. Correct the error and repeat till the program runs correctly. 30
  • 31.
    TO-DO • Check youriClicker grades in Moodle. • Study zyBook chapter 1-3 (content for exam) • Communicate with us using only Moodle forum or Piazza. • Start Project 2 early - seek help in office hours. • Start zyBooks chapter 4 exercises. 31
  • 32.
    COMPSCI 121: DATATYPES & BRANCHING FALL 19
  • 33.
    GOALS FOR TODAY’SCLASS You are now familiar with Objects and Classes and writing programs to solve a problem. We now work with the “building blocks” or syntax of the Java programming language: • Review conditional statements • The Random method • Characters & Strings 2
  • 34.
    REVIEW: CONDITIONAL IFSTATEMENTS First evaluate (alpha > beta): (2 > 1) TRUE If true – follow true branch, if false – do nothing or follow else branch The condition is TRUE so we execute the true branch: eta = alpha + 2 = 2 + 2 = 4 gamma = alpha + 5 = 2 + 5 = 7 3 int alpha = 2, beta = 1, delta = 3, eta = 0, gamma = 0;
  • 35.
    Think - Pair-Share 4 int alpha = 2; int beta = 1, int delta = 3, int eta = 0, int gamma = 0; Evaluate these statements and determine the value of all variables used.
  • 36.
    EXPLANATION For if statement,determine whether true or false First we evaluate (alpha > delta): (2 > 3) FALSE If true – follow true branch, if false – do nothing or follow else branch The condition is FALSE so we follow the else branch. gamma = beta + 5 = 1 + 5 = 6 Next sequential statement is always executed: eta = beta + 2 = 1 + 2 = 3 5
  • 37.
    CLICKER QUESTION 1 if(omega > kappa) { if (alpha > delta) eta = 5; else eta = 4; } else if (alpha < delta) eta = 3; else eta = 2; 6 Evaluate the statements and determine the value of eta given: int alpha = 2, delta = 3, eta = 0; double omega = 2.5, kappa = 3.0; A. 2 B. 3 C. 4 D. 5
  • 38.
    CLICKER QUESTION 1ANSWER if (omega > kappa) { if (alpha > delta) eta = 5; else eta = 4; } else if (alpha < delta) eta = 3; else eta = 2; 7 Evaluate the statements and determine the value of eta given: int alpha = 2, delta = 3, eta = 0; double omega = 2.5, kappa = 3.0; A. 2 B. 3 C. 4 D. 5 FALSE TRUE
  • 39.
    To generate randomnumbers- e.g., to simulate real-world situation, gaming, etc. see DiceRoll.java THE RANDOM CLASS Returns a random number 8 call nextInt() method Import statement New instance
  • 40.
    To generate randomnumbers- e.g., to simulate real-world situation, gaming, etc. see DiceRoll.java THE RANDOM CLASS Returns 10 possible values from 0 to 9 9
  • 41.
    10 OTHER USES OFnextInt METHOD Generates any 6 values starting at 10.
  • 42.
    11 OTHER USES OFnextInt METHOD With a specific seed, each program run will yield the same sequence of pseudo-random numbers. Set the seed declare int variable
  • 43.
    CLICKER QUESTION #2 Whichof the following will work like flipping a coin and getting us 0 and 1 (heads/tail)? A. randGen.nextInt(0); B. randGen.nextInt(1); C. randGen.nextInt(2); D. randGen.nextInt(3); 12
  • 44.
    CLICKER QUESTION #2ANSWER Which of the following will work like flipping a coin? A. randGen.nextInt(0); Error: bound must be positive B. randGen.nextInt(1); Gives 0; C. randGen.nextInt(2); Gives 0/1 (heads/tails) D. randGen.nextInt(3); Gives 0, 1, or 2 13
  • 45.
  • 46.
    String References 1INTRODUCTIONTO REFERENCES String greeting = new String("hi"); String greeting2 = new String("hello"); greeting = greeting2; “hi" :String greeting “hello" :String greeting2 greeting :String “hello" :String greeting2 15
  • 47.
    REFERENCES WITH STRINGLITERALS String greeting = "bonjour"; String greeting2 = "bonjour"; “bonjour" :String greeting greeting2 16
  • 48.
    IDENTITY vs EQUALITY(STRINGS) == tests identity input1==input2 false! == is not true here (different objects) "bye" :String "bye" :String input1 == ? input2 String input1 = new String(”bye"); String input2 = new String(”bye"); 17
  • 49.
    IDENTITY VS EQUALITY(STRINGS) equals tests equalityinput1.equals(input2) TRUE! Only use "==" to test if whole numbers or characters are equal. For String use the method equals "bye" :String input1 "bye" :String equals ? input2 18
  • 50.
    EQUALITY OPERATORS: SUMMARY Checkswhether two operands' values are the same (==) or different (!=). Evaluates to a Boolean value: TRUE or FALSE. Also useful for checking expressions e.g. 19
  • 51.
    CLICKER QUESTION #3 Stringname1 = "Grace Hopper"; String name2 = new String("Grace Hopper"); Evaluate: name1 == name2 A. True B. False C. Maybe D. Don’t know 20
  • 52.
    CLICKER QUESTION #3ANSWER String name1 = "Grace Hopper"; String name2 = new String("Grace Hopper"); Evaluate: name1 == name2 A. True B. False C. Maybe D. Don’t know Evaluate: name1.equals( name2) Ans: TRUE 21
  • 53.
    Scanner console =new Scanner(System.in); Scanner object means: input from keyboard console.nextInt()--- looking for int value console.nextDouble()--- looking for double value console.next() --- looking for String value console.nextLine() --- looking for a whole line https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html REVIEW: SCANNER CLASS METHODS 22
  • 54.
    CLICKER QUESTION #4 A.String phrase = sc.nextInt(); B. String phrase = sc.nextLine(); C. String phrase = sc.nextPhrase; D. String phrase = sc.nextLine; E. String phrase = sc.nextString(); Scanner sc = new Scanner(System.in);     System.out.println(”Enter first phrase"); Which choice retrieves all that is typed? 23
  • 55.
    CLICKER QUESTION #4ANSWER A.String phrase = sc.nextInt(); For ints B. String phrase = sc.nextLine(); C. String phrase = sc.nextPhrase; No such method D. String phrase = sc.nextLine; Missing () E. String phrase = sc.nextString(); No such method Scanner sc = new Scanner(System.in);     System.out.println(”Enter first phrase"); Which choice retrieves all that is typed? 24
  • 56.
    TO-DO • Check youriClicker grades in Moodle. • Study zyBook chapter 1-3 (content for exam) • Communicate with us using only Moodle forum or Piazza. • Start Project 2 early - seek help in office hours. • Start zyBooks chapter 4 exercises. • Read ALL the exam instructions sent to you. 25