Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.8 Additional String Operations | 129

*Basili, V. R., and Selby, R. W., “Comparing the Effectiveness of Software Testing Strategies,”IEEE Transactions
on Software Engineering, Vol. SE–13, No. 12, pp. 1278–1296, Dec. 1987.


Because substringreturns a value of type String, you can use it with the concatenation
operator (+) to copy pieces of strings and join them together to form new strings. The indexOf
and lengthmethods can be useful in determining the location and end of a piece of a string
passed to substringas an argument.
Here is a code segment that uses several of the Stringoperations:


fullName = "Jonathan Alexander Peterson Jr.";
startPos = fullName.indexOf("Peterson");
name = "Mr. "+ fullName.substring(startPos, fullName.length());


This code assigns "Mr. Peterson Jr."to name. First, it stores a string into the variable fullName.
Then, it uses indexOfto locate the start of the name Petersonwithin the string. Next, it builds
a new string by concatenating the literal "Mr. "with the characters “Peterson Jr.”, which are
copied from the original string. As we will see in later chapters, string operations are an im-
portant aspect of many computer applications.


Understanding Before Changing


When you are trying to get an application to run and you come across an error, it’s tempting
to start changing parts of the code in an attempt to make it work.Don’t!You’ll nearly always
make matters worse. It’s essential that you understand what is causing the error and that you
carefully think through the solution. The only thing you should try is running the application
with different data to determine the pattern of the unexpected behavior.
No magic trick—inserting an extra semicolon or right brace, for example—can automatically
fix a coding error. If the compiler tells you that a semicolon or a right brace is missing, you need
to examine the code in light of the syntax rules and determine precisely what the problem is.
Perhaps you accidentally typed a colon instead of a semicolon. Or maybe you included an extra
left brace.
If the source of a problem isn’t immediately obvious, a good rule of thumb is to leave the
computer and go somewhere where you can quietly look over a printed copy of the code.
Studies show that people who do all of their debugging away from the computer actually get
their code to work in less time and ultimately produce better codethan those who continue to
work on the machine—more proof that there is still no mechanical substitute for human
thought.*
Free download pdf