Page 206 - Introduction to Programming with Java: A Problem Solving Approach
P. 206
172
Chapter 5 Using Pre-Built Methods
Now the output looks like this: Output:
that is the question;
THAT IS THE QUESTION;
Note how the trim method strips the leading space from hamlet2’s string. Also note how the toUpperCase method returns an all-uppercase version of hamlet2.
Insertion
To make an insertion, you must know where you want to make it. If you don’t already know the index of where you want the insertion to start, you can find it by using the indexOf method with a unique substring argument. Then extract the substring up to that index, concatenate the desired insertion, and concatenate the substring after that index. The following code fragment performs two insertions within a string. More specifi- cally, the code fragment starts with a philosophy espoused by 17th century French mathematician and philos- opher Renéé Descartes: “All nature will do as I wish it.” It then inserts two strings and transforms the message into a starkly contrasting quote from Charles Darwin: “All nature is perverse & will not do as I wish it.” 5
String descartes = "All nature will do as I wish it.";
String darwin;
int index;
index = descartes.indexOf("will");
darwin = descartes.suAbsptraing(o0, iPndDexF) + Enhancer "is perverse & " +
descartes.substring(index);
index = darwin.indexOf("do");
darwin = darwin.substring(0, index) +
"not " +
darwin.substring(index);
System.out.println(darwin);
Output:
All nature is perverse & will not do as I wish it.
5.7 Formatted Output with the printf Method
You’ve used the System.out.print and System.out.println methods for quite a while now. They
work fine most of the time, but there’s a third System.out method that you’ll want to use every now and
5Charles Darwin’s Letters, edited by Frederick Burkhardt, Cambridge (1996). Charles Darwin started college at the University of Edinburgh in 1825, studying to be a medical doctor like his father. A medical career didn’t appeal to him, so he transferred to Cam- bridge University, where he earned a B.A. in preparation for a career as a country parson. But what he really enjoyed was searching for bugs in the family barn. Right after his graduation, and before he began his first job as a country parson, family connections, a good reference from a college professor, and a pleasant personality gave him the chance to travel around the world as the companion of a brilliant sea captain named Robert FitzRoy (who later invented weather forecasting). This trip launched Darwin’s career as one of the most influential scientists of the modern world.