Documentos de Académico
Documentos de Profesional
Documentos de Cultura
12/16/14
Wellesley High School
15.4 Problem Set
2. Write code segments that perform the following tasks:
a. Replace every blank space character in the string str with a newline character
('\n').
String str = The rain in Spain falls mainly on the plain;
System.out.println(str.replace( , \n));
b. Find the index of the first instance of the substring "the" in the string str.
String str = The rain in Spain falls mainly on the plain;
System.out.println(str.indexOf(the, 0);
c. Find the index of the first instance of the substring "the" after the midpoint of
the string str.
String str = The rain in Spain falls mainly on the plain;
System.out.println(str.indexOf(the, 22);
d. Count the number of instances of the whole word "the" in the string str.
String str = "The rain in Spain falls mainly on the plain";
int begin, end, count;
begin = 0; count = 0;
while(begin < str.length()){
end = str.indexOf(" ", begin);
if(end == -1)
end = str.length();
String word = str.substring(begin, end);
System.out.println(word);
if(word.equals("the")){
count++;
}
begin = end + 1;
}
System.out.println("number of instances of the word
'the': " + count);
Written Questions
1. List the three logical operators
&& (and)
|| (or)
!= (not)
2. Construct a truth table for the expression P or not Q
P
Q
P || (!=Q)
True
True
True
True
False
True
False
True
False
False
False
True
3. Suppose P is true and Q is false. What is the value of the expression P AND NOT Q?
True
4.
23.
}
24.
25.
else{
26.
System.out.println("your number is not
between or on the lower and upper bounds");
27.
}
28.
}
29. }
7. Give an example of an assertion and show how it can be checked with Javas
assert statement.
int x = 0;
Assert x != 0
-this will halt the program because assert x != 0 means that it should be halted if
x=0
8. Explain the role that variant and invariant assertions play in showing that a
loop is correct.