SlideShare a Scribd company logo
COMPSCI 121: BRANCHES
FALL 19
BYTE FROM COMPUTING HISTORY
In 1987, computer scientist Anita Borg
combined technical expertise with a
vision to inspire, motivate, and
encourage women in technology. She
founded a digital community for women
in computing.
Read more about her mission.
2
YOU CAN DO IT!
3
• There is no geek gene!
• You are capable of learning
programming with motivation and
proper practice.
• You can apply computing in your
chosen career: Art, Film, Biology,
Math, Physics, Astronomy…...
CONGRATULATIONS ON THE SKILLS YOU HAVE GAINED!
Analysis - Problem Solving
Design - Creativity
Coding - Computational Thinking
Testing - Rigour
Debugging - Persistence
4
GOALS FOR TODAY’S CLASS
More nuts & bolts of programming!
• More if-else
• Conditional expressions
• Logical Operators
• Short circuit evaluations
• Boolean data types
5
REVIEW - IF-ELSE STATEMENTS
6
An if-else statement executes one group of statements when an
expression is true, and another group of statements when the
expression is false.
EXAMPLE PROBLEM
Write a program that checks the user age and prints
"Enjoy your early years." if the user is less than 16 years.
It prints "You are old enough to drive." if the user is over
the age of 15 but less than 17 years of age. It prints "You
are old enough to vote." if the user is over 17 years of age
but less 24 years of age. It prints "Most car rental
companies will rent to you." if the user is over the age of
24 but less than 34 years of age. If the user is over the
age of 34, it prints "You can run for president.".
7
INTRODUCTION TO FLOW CHARTS
8
FLOW CHART
FOR EXAMPLE
PROBLEM
9
EXAMPLE CODE
10
May print
multiple
statements
REVIEW: NESTED IF-ELSE
Branch statements can include another if-else statement.
11
Draw a
flowchart
CLICKER QUESTION 1
12
salesType = 2;
salesBonus = 7;
What is the the final
value of
salesBonus?
A. 7
B. 8
C. 9
D. 10
CLICKER QUESTION 1 ANSWER
13
salesType = 2;
salesBonus = 7;
What is the the final
value of salesBonus?
A. 7
B. 8
C. 9
salesBonus is 7 + 2, or 9
D. 10
TRUE
TRUE
FALSE
CLICKER QUESTION 2
14
A. Annual price: $2100
B. Annual price: $2350
C. Annual price: $0
D. Annual price: $4800
What is the output of the code if the age of the user is 46?
CLICKER QUESTION 2 ANSWER
15
What is the output of the code
if the age of the user is 46?
A. Annual price: $2100
B. Annual price: $2350
C. Annual price: $0
D. Annual price: $4800
Note
age
ranges
REVIEW: EQUALITY AND RELATIONAL OPERATORS
16
Equality operator checks whether two operands' values are the same
(==) or different (!=). Note that equality is ==, not just =
Relational operator checks how one operand's value relates to another
e.g. being greater than.
CLICKER QUESTION 3
A. 5 is greater than 3
B. 5 is not greater than 3
C. 3 is not greater than 5
D. Error
17
CLICKER QUESTION 3 ANSWER
A. 5 is greater than 3
B. 5 is not greater than 3
C. 3 is not greater than 5
D. Error
18
>=
LOGICAL OPERATORS
&& and
|| or
! Not
1. x > 0 && x < 10 is true (when x is greater
than zero AND less than 10)
2. isEven || n % 2 == 0 is true (if EITHER
condition is true)
3. !isEven is true (if isEven is NOT true.)
19
BOOLEAN DATA TYPE
Boolean variable may be set
using true or false keywords.
20
Don't have to write if (evenFlag == true)
CLICKER QUESTION 4
boolean var1 = true;
boolean var2 = false;
System.out.println((var2 && var1));
21
A. 0
B. 1
C. true
D. false
E. error
CLICKER QUESTION 4 ANSWER
boolean var1 = true;
boolean var2 = false;
System.out.println((var2
&& var1));
22
A. 0
B. 1
C. true
D. false
E. error
TERNARY OPERATOR - CONDITIONAL EXPRESSIONS
23
condition ? exprWhenFalse.
exprWhenTrue :
NOTE: ()
around first
expression
SHORT CIRCUIT EVALUATION
Only evaluates the second operand if necessary.
true || anything is always true
false && anything is always false
!(A && B) is the same as !A || !B
!(A || B) is the same as !A && !B
!(x < 5 && y == 3) is the same as x >= 5 || y != 3
If I don't want the case where x is less than 5 AND y is 3, then I need
x to be greater than OR equal to 5, or I need y to be anything but 3.
24
De Morgan's laws
CLICKER QUESTION 5
((x > 2) || (y < 4)) && (z == 10)
Given x = 4, y = 1, and z = 10, which
comparisons are evaluated?
A. Error
B. (x>2), (y<4) and (z==10)
C. (x>2) and (z==10)
D. (x>2) and (y <4)
25
CLICKER QUESTION 5
((x > 2) || (y < 4)) && (z == 10)
Given x = 4, y = 1, and z = 10, which
comparisons are evaluated?
A. Error
B. (x>2), (y<4) and (z==10)
C. (x>2) and (z==10)
D. (x>2) and (y <4)
26
(4 > 2) is true
so OR operator
evaluates to true
(z == 10) is
evaluated to
determine final
result.
GOOD PROGRAMMING PRACTICES
1. Design before you code- i.e. think and plan what you
will code first.
2. Don’t write all of the code at once. Implement the
outline, or “skeleton” of the code.
3. Incremental development- fill in the smaller parts one
at a time. Debug and test the smaller parts before
moving on.
4. Use the debugger- integral part of development.
27
TO-DO LIST:
• Check your iClicker grades in Moodle.
• Complete zyBook chapter 4-5 exercises.
• Communicate with us using only Moodle forum or
Piazza.
• Upload Project 2 before the deadline!
28
COMPSCI 121: BRANCHES
FALL 19
GOALS FOR TODAY’S CLASS
Demo: PROJECT 3
More nuts & bolts of programming!
• String and Character operations
• Switch statement
• String comparisons and character access
2
REVIEW: RANDOM CLASS
3
You can also pass a
programmer-defined range.
See zyBooks 4.10.
PROJECT 3 OVERVIEW
Note: 2 constructors
Note: private method
4
0, 1, 2
PROJECT 3 OVERVIEW
5
Given the output of a random number generator, how
can you translate that output to Strings such as “A”,
“B”, “C”, where each String is equally likely?
0, 1, 2, 3, 4, 5, 6, 7, 8
“A”, “B”, “C” “A”, “B”, “C”
Easier:
3 ints
generated.
9 ints
generated.
PROJECT 3 MAIN CLASS
1. Creates new instance of StickWaterFireGame called
game.
2. Sets up Scanner and prompts user.
3. Calls methods getScoreReportStr(),
playerWinning(), getComputerChoice(),
computerWinning(), isTie() playRound()
4. Prints messages to player
6
1. Cannot access
private method
getRandomChoi
ce()
2. Does not call
isValidInput
- which is called
internally only by
playRound.
IMPORTANT REMINDERS FOR PROJECTS
1. Start early.
2. Submit often in Gradescope.
3. Keep track of the deadline and grace period to
submit to Gradescope.
4. Attend office hours or ask for help in Piazza (no
showing code).
5. Use the debugger.
6. Read the Tips & FAQs doc and other resources in
Moodle.
7. Use a search engine and/or Java API. 7
TIP: WRITING CONCISE
STATEMENTS
Instead of writing
multiple return
statements you
should
1. declare a variable,
2. set its value
according to the
condition,
3. and use 1 return
statement.
8
Example from a
previous project.
SWITCH STATEMENT
9
SWITCH WITH BREAK: EXAMPLE
10
switch(grade) {
case 'A' :
         System.out.println("Excellent!");
break;
   case 'B' :
   case 'C' :
        System.out.println("Well done");
         break;
   case 'D' :
          System.out.println("You passed");
   case 'F' :
          System.out.println("Better try again");
          break;
    default :
          System.out.println("Invalid grade");}
System.out.println("Your grade is " + grade);
End
Switch
Break statement
SWITCH STATEMENT- KEEP IN MIND
• Duplicate case values are not allowed.
• The value for a case must be the same data type as the
variable in the switch.
• The value for a case must be a constant or a literal.
Variables are not allowed.
• The break statement is used inside the switch to terminate
a statement sequence.
• The break statement is optional. If omitted, execution will
continue on into the next case.
• The default statement is optional, and it must appear at the
end of the switch.
11
CLICKER QUESTION 1
A. User wants to visit Corfu
User wants to visit Crete
B. User wants to visit Crete
C. Unknown Island
D. User wants to visit Corfu 12
What is the output?
CLICKER QUESTION 1 ANSWER
A. User wants to visit Corfu
User wants to visit Crete
B. User wants to visit Crete
C. Unknown Island
D. User wants to visit Corfu
E. Error 13
switch(island) {
case "Corfu":
   System.out.println("User wants to visit Corfu");
case "Crete":
   System.out.println("User wants to visit Crete");break;
case "Santorini":
   System.out.println("User wants to visit Santorini");break;
default:
   System.out.println("Unknown Island");}
String island = "Corfu";
2 statements printed
as missing break
after first case.
CHARACTER CLASS STATIC METHODS
Character.isDigit
Character.isLetter
Character.isLetterOrDigit
Character.isLowerCase
Character.isUpperCase
Character.isWhitespace
Character.toLowerCase
Character.toUpperCase
14
● Must use
Character.method
Name
● Static methods do not
need objects to be
created.
● All methods return
values.
CHARACTER CLASS: EXAMPLES - T-P-S
15
char value1 = '9';
System.out.println(Character.isDigit(value1));
 
char value2 = '*';
System.out.println(Character.isLetterOrDigit(value2));
char value3 = ';';
System.out.println(Character.isLetter(value3));
char value4 = ' ';
System.out.println(Character.isLetter(value4));
All functions evaluate to TRUE or FALSE
STRING ACCESS: RECALL
Each string character has a position number called
an index, starting with 0 (not 1)
String pupName = “Spot”;
char ch = pupName.charAt(1);
// ch is assigned ‘p’
ch = pupName.charAt(0);
// ch  is assigned ‘S’ 16
CHARACTER CLASS: EXAMPLE
17
String str = “Cheese”;
char char1 = str.charAt(1);
h
char char2 = Character.toUpperCase(char1);
H
Each character in a String has an index number.
CLICKER QUESTION 2
18
Consider this string:
String str = “Hi 357 times!!”;
Which one of the following returns true?
A. Character.isWhitespace(str.charAt(6));
B. Character.isDigit(str.charAt(6));
C. Character.isLetter(str.charAt(5));
D. Character.isLowerCase(str.charAt(0));
CLICKER QUESTION 2 - ANSWER
19
String str = “Hi 357 times!!”;
Which one of the following returns True?
A. Character.isWhitespace(str.charAt(6));True
B. Character.isDigit(str.charAt(6)); False
C. Character.isLetter(str.charAt(5)); False
D. Character.isLowerCase(str.charAt(0)); False
WORKING WITH STRINGS
PROBLEM: Find the last character in the string
“Supercalifragilisticexpialidocious”.
SOLUTION: Find the character at length of string -1.
20
Also written as above.
CLICKER QUESTION 3
21
Consider these statements about a String called str:
Character.isLetter(str.charAt(5)); True
Character.toUpperCase(str.charAt(10)); A
Character.isWhitespace(str.charAt(13)); True
Which one of the following Strings below could be str?
A. Give me your doughnuts.
B. What on earth is that?
C. Call me a cab, dude.
D. I found Ada’s code!
CLICKER QUESTION 3
22
Consider these statements about a String called str:
Character.isLetter(str.charAt(5)); TRUE
Character.toUpperCase(str.charAt(10)); A
Character.isWhitespace(str.charAt(13)); TRUE
Which one of the following Strings below could be str?
D. I found Ada’s code!
WORKING WITH STRINGS
PROBLEM: How to join 2 Strings (st1 and st2)
SOLUTION: Use the + operator or use st1.concat(st2)to return a new
string that appends st2 to st1.
23
INDEXOF METHOD
24
Where in the string to start looking.
Also has
lastIndexOf(item)
true
SUBSTRING OPERATIONS
T-P-S
What does fruit.substring(4, 6) return ?
25
substring(startI
ndex, endIndex)
returns substring
starting at
startIndex and
ending at
endIndex - 1.
Length of the substring
is given by endIndex
- startIndex.
CLICKER QUESTION 4
String str = “I ordered the large coffee, not the
small tea.”;
String subStr = str.substring(10, str.length());
What is the value of subStr?
A. the large coffee, not the small tea
B. the large coffee, not the small tea.
C. Error, index out of bounds.
D. he large coffee, not the small tea. 26
CLICKER QUESTION 4-ANSWER
27
String str = “I ordered the large coffee, not the
small tea.”;
String subStr = str.substring(10, str.length());
What is the value of subStr?
A. the large coffee, not the small tea
B. the large coffee, not the small tea.
C. Error, index out of bounds.
D. he large coffee, not the small tea.
COMPARING STRINGS
28
Return value from compareTo is difference between first characters in the strings that differ.
If the strings are equal, their difference is zero.
If the first string (the one on which the method is invoked) comes first in the alphabet, the
difference is negative.
Otherwise, the difference is positive.
CLICKER QUESTION 5
A. All negative values
B. All positive values
C. Negative, negative, positive, zero
D. Positive, negative, positive, zero
a compareTo(b) ->
b compareTo(c) ->
c compareTo(a) ->
c compareTo(c) ->
29
CLICKER QUESTION 5 ANSWERS
A. All negative values
B. All positive values
C. Negative, negative, positive, zero
D. Positive, negative, positive, zero
a compareTo(b) -> negative value
b compareTo(c) -> negative value
c compareTo(a) -> positive value
c compareTo(c) -> zero
30
TO-DO LIST:
• Check your iClicker grades in Moodle.
• Complete zyBook chapter 5 exercises.
• Communicate with us using only Moodle forum
or Piazza. Course staff do NOT answer emails.
• Work on Project 3.
31

More Related Content

PPT
Java Programmin: Selections
PDF
DOCX
1 Midterm Preview Time allotted 50 minutes CS 11.docx
PPT
conditional statements
PDF
Week 4
PDF
Week 1
DOCX
Review questions and answers
Java Programmin: Selections
1 Midterm Preview Time allotted 50 minutes CS 11.docx
conditional statements
Week 4
Week 1
Review questions and answers

Similar to Week 5 (20)

PPTX
Icom4015 lecture4-f17
PPT
00_Introduction to Java.ppt
PPT
Comp102 lec 5.1
PPTX
JPC#8 Introduction to Java Programming
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
PDF
Programming in Java: Control Flow
PPT
PPT
Introduction to Java Programming Part 2
PPSX
Java session4
PPT
Chapter 2&3 (java fundamentals and Control Structures).ppt
PPTX
Java chapter 3
PPTX
ICSE Class X Conditional Statements in java
PDF
2021 icse reducedsylabiix-computer applications
PPTX
Pi j1.3 operators
PPT
ch04-conditional-execution.ppt
PDF
Chapter 00 revision
PPT
03slide.ppt
PDF
Test bank for Big Java: Early Objects 6th Edition by Horstmann
PDF
Java input Scanner
DOC
03review
Icom4015 lecture4-f17
00_Introduction to Java.ppt
Comp102 lec 5.1
JPC#8 Introduction to Java Programming
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Programming in Java: Control Flow
Introduction to Java Programming Part 2
Java session4
Chapter 2&3 (java fundamentals and Control Structures).ppt
Java chapter 3
ICSE Class X Conditional Statements in java
2021 icse reducedsylabiix-computer applications
Pi j1.3 operators
ch04-conditional-execution.ppt
Chapter 00 revision
03slide.ppt
Test bank for Big Java: Early Objects 6th Edition by Horstmann
Java input Scanner
03review
Ad

More from EasyStudy3 (20)

PDF
Week 7
PDF
Chapter 3
PDF
Week 6
PDF
2. polynomial interpolation
PDF
Chapter2 slides-part 2-harish complete
PDF
PDF
Chapter 5
PDF
Lec#4
PDF
Chapter 12 vectors and the geometry of space merged
PDF
Week 5
PDF
Chpater 6
PDF
Chapter 5
PDF
Lec#3
PDF
Chapter 16 2
PDF
Chapter 5 gen chem
PDF
Topic 4 gen chem guobi
PDF
Gen chem topic 3 guobi
PDF
Chapter 2
PDF
Gen chem topic 1 guobi
Week 7
Chapter 3
Week 6
2. polynomial interpolation
Chapter2 slides-part 2-harish complete
Chapter 5
Lec#4
Chapter 12 vectors and the geometry of space merged
Week 5
Chpater 6
Chapter 5
Lec#3
Chapter 16 2
Chapter 5 gen chem
Topic 4 gen chem guobi
Gen chem topic 3 guobi
Chapter 2
Gen chem topic 1 guobi
Ad

Recently uploaded (20)

PDF
Pre independence Education in Inndia.pdf
PPTX
master seminar digital applications in india
PDF
Computing-Curriculum for Schools in Ghana
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Institutional Correction lecture only . . .
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Structure & Organelles in detailed.
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Pharma ospi slides which help in ospi learning
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Classroom Observation Tools for Teachers
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pre independence Education in Inndia.pdf
master seminar digital applications in india
Computing-Curriculum for Schools in Ghana
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Institutional Correction lecture only . . .
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Microbial diseases, their pathogenesis and prophylaxis
RMMM.pdf make it easy to upload and study
Cell Structure & Organelles in detailed.
Basic Mud Logging Guide for educational purpose
Pharma ospi slides which help in ospi learning
O5-L3 Freight Transport Ops (International) V1.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Classroom Observation Tools for Teachers
TR - Agricultural Crops Production NC III.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape

Week 5

  • 2. BYTE FROM COMPUTING HISTORY In 1987, computer scientist Anita Borg combined technical expertise with a vision to inspire, motivate, and encourage women in technology. She founded a digital community for women in computing. Read more about her mission. 2
  • 3. YOU CAN DO IT! 3 • There is no geek gene! • You are capable of learning programming with motivation and proper practice. • You can apply computing in your chosen career: Art, Film, Biology, Math, Physics, Astronomy…...
  • 4. CONGRATULATIONS ON THE SKILLS YOU HAVE GAINED! Analysis - Problem Solving Design - Creativity Coding - Computational Thinking Testing - Rigour Debugging - Persistence 4
  • 5. GOALS FOR TODAY’S CLASS More nuts & bolts of programming! • More if-else • Conditional expressions • Logical Operators • Short circuit evaluations • Boolean data types 5
  • 6. REVIEW - IF-ELSE STATEMENTS 6 An if-else statement executes one group of statements when an expression is true, and another group of statements when the expression is false.
  • 7. EXAMPLE PROBLEM Write a program that checks the user age and prints "Enjoy your early years." if the user is less than 16 years. It prints "You are old enough to drive." if the user is over the age of 15 but less than 17 years of age. It prints "You are old enough to vote." if the user is over 17 years of age but less 24 years of age. It prints "Most car rental companies will rent to you." if the user is over the age of 24 but less than 34 years of age. If the user is over the age of 34, it prints "You can run for president.". 7
  • 11. REVIEW: NESTED IF-ELSE Branch statements can include another if-else statement. 11 Draw a flowchart
  • 12. CLICKER QUESTION 1 12 salesType = 2; salesBonus = 7; What is the the final value of salesBonus? A. 7 B. 8 C. 9 D. 10
  • 13. CLICKER QUESTION 1 ANSWER 13 salesType = 2; salesBonus = 7; What is the the final value of salesBonus? A. 7 B. 8 C. 9 salesBonus is 7 + 2, or 9 D. 10 TRUE TRUE FALSE
  • 14. CLICKER QUESTION 2 14 A. Annual price: $2100 B. Annual price: $2350 C. Annual price: $0 D. Annual price: $4800 What is the output of the code if the age of the user is 46?
  • 15. CLICKER QUESTION 2 ANSWER 15 What is the output of the code if the age of the user is 46? A. Annual price: $2100 B. Annual price: $2350 C. Annual price: $0 D. Annual price: $4800 Note age ranges
  • 16. REVIEW: EQUALITY AND RELATIONAL OPERATORS 16 Equality operator checks whether two operands' values are the same (==) or different (!=). Note that equality is ==, not just = Relational operator checks how one operand's value relates to another e.g. being greater than.
  • 17. CLICKER QUESTION 3 A. 5 is greater than 3 B. 5 is not greater than 3 C. 3 is not greater than 5 D. Error 17
  • 18. CLICKER QUESTION 3 ANSWER A. 5 is greater than 3 B. 5 is not greater than 3 C. 3 is not greater than 5 D. Error 18 >=
  • 19. LOGICAL OPERATORS && and || or ! Not 1. x > 0 && x < 10 is true (when x is greater than zero AND less than 10) 2. isEven || n % 2 == 0 is true (if EITHER condition is true) 3. !isEven is true (if isEven is NOT true.) 19
  • 20. BOOLEAN DATA TYPE Boolean variable may be set using true or false keywords. 20 Don't have to write if (evenFlag == true)
  • 21. CLICKER QUESTION 4 boolean var1 = true; boolean var2 = false; System.out.println((var2 && var1)); 21 A. 0 B. 1 C. true D. false E. error
  • 22. CLICKER QUESTION 4 ANSWER boolean var1 = true; boolean var2 = false; System.out.println((var2 && var1)); 22 A. 0 B. 1 C. true D. false E. error
  • 23. TERNARY OPERATOR - CONDITIONAL EXPRESSIONS 23 condition ? exprWhenFalse. exprWhenTrue : NOTE: () around first expression
  • 24. SHORT CIRCUIT EVALUATION Only evaluates the second operand if necessary. true || anything is always true false && anything is always false !(A && B) is the same as !A || !B !(A || B) is the same as !A && !B !(x < 5 && y == 3) is the same as x >= 5 || y != 3 If I don't want the case where x is less than 5 AND y is 3, then I need x to be greater than OR equal to 5, or I need y to be anything but 3. 24 De Morgan's laws
  • 25. CLICKER QUESTION 5 ((x > 2) || (y < 4)) && (z == 10) Given x = 4, y = 1, and z = 10, which comparisons are evaluated? A. Error B. (x>2), (y<4) and (z==10) C. (x>2) and (z==10) D. (x>2) and (y <4) 25
  • 26. CLICKER QUESTION 5 ((x > 2) || (y < 4)) && (z == 10) Given x = 4, y = 1, and z = 10, which comparisons are evaluated? A. Error B. (x>2), (y<4) and (z==10) C. (x>2) and (z==10) D. (x>2) and (y <4) 26 (4 > 2) is true so OR operator evaluates to true (z == 10) is evaluated to determine final result.
  • 27. GOOD PROGRAMMING PRACTICES 1. Design before you code- i.e. think and plan what you will code first. 2. Don’t write all of the code at once. Implement the outline, or “skeleton” of the code. 3. Incremental development- fill in the smaller parts one at a time. Debug and test the smaller parts before moving on. 4. Use the debugger- integral part of development. 27
  • 28. TO-DO LIST: • Check your iClicker grades in Moodle. • Complete zyBook chapter 4-5 exercises. • Communicate with us using only Moodle forum or Piazza. • Upload Project 2 before the deadline! 28
  • 30. GOALS FOR TODAY’S CLASS Demo: PROJECT 3 More nuts & bolts of programming! • String and Character operations • Switch statement • String comparisons and character access 2
  • 31. REVIEW: RANDOM CLASS 3 You can also pass a programmer-defined range. See zyBooks 4.10.
  • 32. PROJECT 3 OVERVIEW Note: 2 constructors Note: private method 4
  • 33. 0, 1, 2 PROJECT 3 OVERVIEW 5 Given the output of a random number generator, how can you translate that output to Strings such as “A”, “B”, “C”, where each String is equally likely? 0, 1, 2, 3, 4, 5, 6, 7, 8 “A”, “B”, “C” “A”, “B”, “C” Easier: 3 ints generated. 9 ints generated.
  • 34. PROJECT 3 MAIN CLASS 1. Creates new instance of StickWaterFireGame called game. 2. Sets up Scanner and prompts user. 3. Calls methods getScoreReportStr(), playerWinning(), getComputerChoice(), computerWinning(), isTie() playRound() 4. Prints messages to player 6 1. Cannot access private method getRandomChoi ce() 2. Does not call isValidInput - which is called internally only by playRound.
  • 35. IMPORTANT REMINDERS FOR PROJECTS 1. Start early. 2. Submit often in Gradescope. 3. Keep track of the deadline and grace period to submit to Gradescope. 4. Attend office hours or ask for help in Piazza (no showing code). 5. Use the debugger. 6. Read the Tips & FAQs doc and other resources in Moodle. 7. Use a search engine and/or Java API. 7
  • 36. TIP: WRITING CONCISE STATEMENTS Instead of writing multiple return statements you should 1. declare a variable, 2. set its value according to the condition, 3. and use 1 return statement. 8 Example from a previous project.
  • 38. SWITCH WITH BREAK: EXAMPLE 10 switch(grade) { case 'A' :          System.out.println("Excellent!"); break;    case 'B' :    case 'C' :         System.out.println("Well done");          break;    case 'D' :           System.out.println("You passed");    case 'F' :           System.out.println("Better try again");           break;     default :           System.out.println("Invalid grade");} System.out.println("Your grade is " + grade); End Switch Break statement
  • 39. SWITCH STATEMENT- KEEP IN MIND • Duplicate case values are not allowed. • The value for a case must be the same data type as the variable in the switch. • The value for a case must be a constant or a literal. Variables are not allowed. • The break statement is used inside the switch to terminate a statement sequence. • The break statement is optional. If omitted, execution will continue on into the next case. • The default statement is optional, and it must appear at the end of the switch. 11
  • 40. CLICKER QUESTION 1 A. User wants to visit Corfu User wants to visit Crete B. User wants to visit Crete C. Unknown Island D. User wants to visit Corfu 12 What is the output?
  • 41. CLICKER QUESTION 1 ANSWER A. User wants to visit Corfu User wants to visit Crete B. User wants to visit Crete C. Unknown Island D. User wants to visit Corfu E. Error 13 switch(island) { case "Corfu":    System.out.println("User wants to visit Corfu"); case "Crete":    System.out.println("User wants to visit Crete");break; case "Santorini":    System.out.println("User wants to visit Santorini");break; default:    System.out.println("Unknown Island");} String island = "Corfu"; 2 statements printed as missing break after first case.
  • 42. CHARACTER CLASS STATIC METHODS Character.isDigit Character.isLetter Character.isLetterOrDigit Character.isLowerCase Character.isUpperCase Character.isWhitespace Character.toLowerCase Character.toUpperCase 14 ● Must use Character.method Name ● Static methods do not need objects to be created. ● All methods return values.
  • 43. CHARACTER CLASS: EXAMPLES - T-P-S 15 char value1 = '9'; System.out.println(Character.isDigit(value1));   char value2 = '*'; System.out.println(Character.isLetterOrDigit(value2)); char value3 = ';'; System.out.println(Character.isLetter(value3)); char value4 = ' '; System.out.println(Character.isLetter(value4)); All functions evaluate to TRUE or FALSE
  • 44. STRING ACCESS: RECALL Each string character has a position number called an index, starting with 0 (not 1) String pupName = “Spot”; char ch = pupName.charAt(1); // ch is assigned ‘p’ ch = pupName.charAt(0); // ch  is assigned ‘S’ 16
  • 45. CHARACTER CLASS: EXAMPLE 17 String str = “Cheese”; char char1 = str.charAt(1); h char char2 = Character.toUpperCase(char1); H Each character in a String has an index number.
  • 46. CLICKER QUESTION 2 18 Consider this string: String str = “Hi 357 times!!”; Which one of the following returns true? A. Character.isWhitespace(str.charAt(6)); B. Character.isDigit(str.charAt(6)); C. Character.isLetter(str.charAt(5)); D. Character.isLowerCase(str.charAt(0));
  • 47. CLICKER QUESTION 2 - ANSWER 19 String str = “Hi 357 times!!”; Which one of the following returns True? A. Character.isWhitespace(str.charAt(6));True B. Character.isDigit(str.charAt(6)); False C. Character.isLetter(str.charAt(5)); False D. Character.isLowerCase(str.charAt(0)); False
  • 48. WORKING WITH STRINGS PROBLEM: Find the last character in the string “Supercalifragilisticexpialidocious”. SOLUTION: Find the character at length of string -1. 20 Also written as above.
  • 49. CLICKER QUESTION 3 21 Consider these statements about a String called str: Character.isLetter(str.charAt(5)); True Character.toUpperCase(str.charAt(10)); A Character.isWhitespace(str.charAt(13)); True Which one of the following Strings below could be str? A. Give me your doughnuts. B. What on earth is that? C. Call me a cab, dude. D. I found Ada’s code!
  • 50. CLICKER QUESTION 3 22 Consider these statements about a String called str: Character.isLetter(str.charAt(5)); TRUE Character.toUpperCase(str.charAt(10)); A Character.isWhitespace(str.charAt(13)); TRUE Which one of the following Strings below could be str? D. I found Ada’s code!
  • 51. WORKING WITH STRINGS PROBLEM: How to join 2 Strings (st1 and st2) SOLUTION: Use the + operator or use st1.concat(st2)to return a new string that appends st2 to st1. 23
  • 52. INDEXOF METHOD 24 Where in the string to start looking. Also has lastIndexOf(item) true
  • 53. SUBSTRING OPERATIONS T-P-S What does fruit.substring(4, 6) return ? 25 substring(startI ndex, endIndex) returns substring starting at startIndex and ending at endIndex - 1. Length of the substring is given by endIndex - startIndex.
  • 54. CLICKER QUESTION 4 String str = “I ordered the large coffee, not the small tea.”; String subStr = str.substring(10, str.length()); What is the value of subStr? A. the large coffee, not the small tea B. the large coffee, not the small tea. C. Error, index out of bounds. D. he large coffee, not the small tea. 26
  • 55. CLICKER QUESTION 4-ANSWER 27 String str = “I ordered the large coffee, not the small tea.”; String subStr = str.substring(10, str.length()); What is the value of subStr? A. the large coffee, not the small tea B. the large coffee, not the small tea. C. Error, index out of bounds. D. he large coffee, not the small tea.
  • 56. COMPARING STRINGS 28 Return value from compareTo is difference between first characters in the strings that differ. If the strings are equal, their difference is zero. If the first string (the one on which the method is invoked) comes first in the alphabet, the difference is negative. Otherwise, the difference is positive.
  • 57. CLICKER QUESTION 5 A. All negative values B. All positive values C. Negative, negative, positive, zero D. Positive, negative, positive, zero a compareTo(b) -> b compareTo(c) -> c compareTo(a) -> c compareTo(c) -> 29
  • 58. CLICKER QUESTION 5 ANSWERS A. All negative values B. All positive values C. Negative, negative, positive, zero D. Positive, negative, positive, zero a compareTo(b) -> negative value b compareTo(c) -> negative value c compareTo(a) -> positive value c compareTo(c) -> zero 30
  • 59. TO-DO LIST: • Check your iClicker grades in Moodle. • Complete zyBook chapter 5 exercises. • Communicate with us using only Moodle forum or Piazza. Course staff do NOT answer emails. • Work on Project 3. 31