Post on 26-Mar-2022
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture8CharactersandStrings
suggestedreading:JavaCh.8.1-8.4
2
Learning Goals•Beabletoconfidentlywriteandcallmethodsthatuseparametersandreturnvalues.
•Beabletogeneraterandomvaluesinyourprograms.
•Beabletouseandmanipulatechars.•Beabletowritestringalgorithmsthatoperateoneachcharacter.
3
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
4
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
13
Example: readInt
int x = readInt(”Your guess? ");
We give readInt some information (the text to
print to the user)
We call readInt
14
Example: readInt
int x = readInt(”Your guess? ");
When we include values in the parentheses of a method call, this means we are passing them as parameters to this
method.
15
Example: readInt
int x = readInt(”Your guess? ");
When finished, readInt gives us information back (the user’s number) and we put it in x.
16
Example: readInt
int x = readInt(”Your guess? ");
When we set a variable equal to a method, this tells Java to save the return value of the method in that variable.
17
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
18
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
Tells Java this method needs two ints in order to
execute.
19
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
Inside drawBox, refer to the first parameter value
as width…
20
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
…and the second parameter value as height.
21
drawBox
drawBox(10, 4);
We give drawBox some information (the size of
the box we want)
We call drawBox
22
drawBox
int width = readInt("Width? ");int height = readInt("Height? ");...
drawBox(width, height);
We give drawBox some information (the size of
the box we want)
We call drawBox
23
drawBox
int width = readInt("Width? "); 7int height = readInt("Height? "); 4...
drawBox(width, height);
24
drawBox
int width = readInt("Width? "); 7int height = readInt("Height? "); 4...
drawBox(width, height);7 4
28
drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
7 4
29
drawBox
private void drawBox(int width, int height) {...println(width); // prints 7println(height); // prints 4...
}
7 4
31
Parameter Namespublic void run() {
int width = readInt("Width? "); 7int height = readInt("Height? "); 4drawBox(width, height);
}
private void drawBox(int width, int height) {...
}
run
width height
7 4drawBox
width height
7 4
32
Parameter Namespublic void run() {
int width = readInt("Width? "); 7int height = readInt("Height? "); 4drawBox(width, height);
}
private void drawBox(int w, int h) {...
}
run
width height
7 4drawBox
w h
7 4
33
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
34
Return Example: metersToCm
private double metersToCm(double meters) {...
}
When this method finishes, it will return a double.
35
Return Example: metersToCm
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
Returns the value of this expression (centimeters).
37
Return Example: metersToCm
public void run() {double cm = metersToCm(10);...
}
Setting a variable equal to a method means we save the method’s return
value in that variable.
38
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
39
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
7
40
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
7
7
41
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
} 700
7
7
42
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
700
7
43
Return Values and Expressionspublic void run() {
double meters = readDouble("# meters? ”);println(metersToCm(meters) + " cm.");
}
private double metersToCm(double meters) {...
}
7
44
Return Values and Expressionspublic void run() {
double meters = readDouble("# meters? ”);println(metersToCm(meters) + " cm.");
}
private double metersToCm(double meters) {...
}
700
You can use a method’s return value directly in an expression.
7
45
Buggy Example!public void run() {
double meters = readDouble("# meters? ”);...
metersToCm(meters); // Does nothing!...
}
7
46
Buggy Example!public void run() {
double meters = readDouble("# meters? ”);...
metersToCm(meters); // Does nothing!...
}
7
700
47
private int max(int num1, int num2) {if(num1 >= num2) {
return num1;}return num2; // here only if num1 < num2
}
Return Stops Method Execution
51
Returning Booleans
private boolean isEven(int number) {return number % 2 == 0;
}
// Examplepublic void run() {
if (isEven(2)) {...
}}
55
Returning Booleans
private boolean isDivisibleBy(int a, int b) {return a % b == 0;
}
// Examplepublic void run() {
if (isDivisibleBy(4, 2)) {...
}}
62
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
result0n i
63
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n i
64
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
65
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
66
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
68
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
1
0! = 1
69
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
70
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
71
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
72
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
73
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
result1n i
0! = 1
74
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n i
0! = 1
75
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
76
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
77
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
78
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
79
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
80
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
81
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
1
0! = 1
82
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
1
0! = 11! = 1
83
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
84
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
85
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
86
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
87
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
2
0! = 11! = 1
88
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
2
0! = 11! = 12! = 2
89
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
90
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
91
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
92
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
93
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
6
0! = 11! = 12! = 2
94
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
6
0! = 11! = 12! = 23! = 6
95
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}4i
0! = 11! = 12! = 23! = 6
96
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}4i
0! = 11! = 12! = 23! = 6
97
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
98
RandomGenerator• import acm.util.*;
// random number from 0-9 inclusiveint digit = RandomGenerator.getInstance().nextInt(0, 9);println(digit);
// prints "hello!" between 3-6 timesint times = RandomGenerator.getInstance().nextInt(3, 6);for (int i = 0; i < times; i++) {
println("hello!");}
Method DescriptionRandomGenerator.getInstance().nextInt(min, max) arandomintegerinthe
givenrange,inclusive
99
RandomGeneratorThe RandomGenerator class defines the following methods:
int nextInt(int low, int high)Returns a random int between low and high, inclusive.
int nextInt(int n)Returns a random int between 0 and n-1.
double nextDouble(double low, double high)Returns a random double d in the range low ≤ d < high.
double nextDouble()Returns a random double d in the range 0 ≤ d < 1.
boolean nextBoolean()Returns a random boolean value, which is true 50 percent of the time.
boolean nextBoolean(double p)Returns a random boolean, which is true with probability p, where 0 ≤ p ≤ 1.
Color nextColor()Returns a random color.
100
Extra: Dice exercise• WriteaconsoleprogramRollTwoDice thatrepeatedlyrollstwo6-sideddiceuntiltheyarriveatagivendesiredsum.
Desired sum? 93 and 4 = 72 and 1 = 35 and 5 = 106 and 2 = 86 and 5 = 114 and 5 = 9
• TrysolvingthisonyourownonCodeStepByStep!
RollTwoDice
101
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
104
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
105
CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.
char letterA = 'A';char plus = '+';char zero = '0';char space = ' ';char newLine = '\n';char tab = '\t';char singleQuote = '\'';char backSlash = '\\';
106
CharUnderthehood,Javarepresentseachchar asaninteger (its“ASCIIvalue”).
•Uppercaselettersaresequentiallynumbered•Lowercaselettersaresequentiallynumbered•Digitsaresequentiallynumbered
char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0'; // Actually 48
107
Char Math!WecantakeadvantageofJavarepresentingeachchar asaninteger (its“ASCIIvalue”):
boolean areEqual = 'A' == 'A'; // trueboolean earlierLetter = 'f' < 'c'; // falsechar uppercaseB = 'A' + 1;int diff = 'c' - 'a'; // 2int numLettersInAlphabet = 'z' – 'a' + 1;// orint numLettersInAlphabet = 'Z' – 'A' + 1;
108
Char Math!WecantakeadvantageofJavarepresentingeachchar asaninteger (its“ASCIIvalue”):
// prints out every characterfor (char ch = 'a'; ch <= 'z'; ch++) {
print(ch);}
109
Char Math!Noteveryintegermapstoacharacter.Sowhenyouhaveanexpressionwithints andchars,Javapicksint asthemostexpressivetype.
'A' + 1 // evaluates to 66 (int)'c' + (2*5) – 1 // evaluates to 108
Wecanmakeitacharbyputtingitinacharvariable.char uppercaseB = 'A' + 1;// orchar uppercaseB = 66;
110
Side Note: Type-castingIfwewanttoforceJavatotreatanexpressionasaparticulartype,wecanalsocastit tothattype.
'A' + 1 // evaluates to 66 (int)(char)('A' + 1) // evaluates to 'B' (char)
1 / 2 // evaluates to 0 (int)(double)1 / 2 // evaluates to 0.5 (double)1 / (double)2 // evaluates to 0.5 (double)
111
Character MethodsTherearesomehelpfulbuilt-inJavamethodstomanipulatechars.
char lowercaseA = 'a';char uppercaseA = Character.toUpperCase(lowercaseA);
char plus = '+';if (Character.isLetter(plus)) {
...}
112
Character MethodsMethod Description
Character.isDigit(ch) trueifch is'0' through'9'
Character.isLetter(ch) trueifch is'a' through'z' or'A' through'Z'
Character.isLetterOrDigit(ch) trueifch is'a' through'z','A' through'Z' or '0' through'9'
Character.isLowerCase(ch) trueifch is'a' through'z'
Character.isUpperCase(ch) trueifch is'A' through'Z'
Character.toLowerCase(ch) returnslowercaseequivalentofaletter
Character.toUpperCase(ch) returnsuppercaseequivalentofaletter
Character.isWhitespace(ch) trueifch isaspace,tab,newline,etc.
Remember: these returnthe new char, they cannot modify an existing char!
113
Character MethodsRemembertoalwayssavethereturnvalueofCharactermethods!
char lowercaseA = 'a';Character.toUpperCase(lowercaseA); // Does nothing!println(lowercaseA); // prints ’a’!
char uppercaseA = Character.toUpperCase(lowercaseA); // OK
println(uppercaseA); // prints ’A’!
114
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
115
StringsAString isavariabletyperepresentingasequenceofcharacters.
String text = "Hi parents!";
– Eachcharacterisassignedanindex,goingfrom0tolength-1– Thereisachar ateachindex
index 0 1 2 3 4 5 6 7 8 9 10
character 'H' 'i' ' ' 'p' 'a' 'r' 'e' 'n' 't' 's' '!'
116
String str = "Hello, world!";String empty = "";println(str);
// Read in text from the userString name = readLine("What is your name? ");
// String concatenation (using “+”)String message = 2 + " cool " + 2 + " handle";int x = 2;println("x has the value " + x);
Creating Strings
117
String str = "Hello, world!";
// Lengthint strLength = str.length(); // 13
// Access individual characterschar firstLetter = str.charAt(0);char lastLetter = str.charAt(strLength – 1);char badTimes = str.charAt(strLength); // ERROR
Common String Operations
118
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String hello = str.substring(0, 5);
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
119
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String worldExclm = str.substring(7, 13);
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
120
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String worldExclm = str.substring(7); // to end
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
121
String MethodsMethodname Description
s.length() numberofcharactersinthisstring
s.charAt(index) charatthegivenindex
s.indexOf(str) indexwherethestartofthegivenstringappearsinthisstring(-1ifnotfound)
s.substring(index1, index2)ors.substring(index1)
thecharactersinthisstringfromindex1 (inclusive)toindex2 (exclusive);ifindex2 isomitted,goesuntilend
s.toLowerCase() anewstringwithalllowercaseletterss.toUpperCase() anewstringwithalluppercaseletters
• Thesemethodsarecalledusingdotnotation:
String className = "CS 106A yay!";println(className.length()); // 12
122
Strings are ImmutableOnceyoucreateaString,itscontentscannotbechanged.
// Cannot change individual chars in the stringString typo = "Hello, warld!”;
TochangeaString,youmustcreateanew Stringcontainingthevalueyouwant(e.g.usingStringmethods).
123
Strings are ImmutableString className = "cs 106a";className.toUpperCase(); // does nothing!
className = className.toUpperCase(); // ✔println(className); // CS 106A
124
Comparing StringsString greeting = "Hello!”;if (greeting == "Hello!") { // Doesn’t work!
...}
// Instead:if (greeting.equals("Hello!")) {
...}
Always use .equals instead of == and !=
125
Comparing StringsMethod Description
s1.equals(s2) whethertwostringscontainthesamecharacters
s1.equalsIgnoreCase(s2) whethertwostringscontainthesamecharacters,ignoringuppervs.lowercase
s1.startsWith(s2) whethers1 containss2’scharactersatstart
s1.endsWith(s2) whethers1 containss2’scharactersatend
s1.contains(s2) whethers2 isfoundwithins1
126
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
String str = "Hello!";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);// Do something with ch here
}
127
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
// Prints out each letter on a separate lineString str = "Hello!";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);println(ch);
}
128
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
// Creates a new String in all capsString str = "Hello!";String newStr = "";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);newStr += Character.toUpperCase(ch);
}println(newStr); // HELLO!