+ All Categories
Home > Documents > mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString ....

mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString ....

Date post: 16-Feb-2018
Category:
Upload: lehanh
View: 220 times
Download: 2 times
Share this document with a friend
26
CS 1302 – Lab 2 This is a tutorial on associations between classes, the String and StringBuilder classes. There are 6 stages to complete this lab: Stag e Title Text Reference 1 One-to-One Associations 10.4 2 One-to-One Association, Bi- directional Navigability 10.4 3 One-to-Many Association 10.4 4 String.split(…) 10.10.3, 10.10.4 5 String.format(…) 10.10.7 6 The StringBuilder Class 10.11 To make this document easier to read, it is recommend that you turn off spell checking in Word: 1. Choose: File, Option, Proofing 2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…” Stage 1 - One-to-One Association In this stage we study a one-to-one association between classes. 1. (Read, no action required) Consider the class diagram shown on the right which shows that a Person has-a Dog. In UML this is indicated by the solid line between the two classes and is called an association (or a has-a relationship). The role name, dog indicates that the Person class has an instance variable, dog of type Dog. The navigability is indicated by the arrow at the end of the association. Since the arrow points to Dog, this indicates that no only does a Person have a Dog, but a reference to the Dog can be obtained through the Person (via the getDog method shown below). The Person class indicated from the class diagram is: public class Person { Dog dog; public Dog getDog() { 1
Transcript
Page 1: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

CS 1302 – Lab 2

This is a tutorial on associations between classes, the String and StringBuilder classes. There are 6 stages to complete this lab:

Stage Title Text Reference1 One-to-One Associations 10.42 One-to-One Association, Bi-directional Navigability 10.43 One-to-Many Association 10.44 String.split(…) 10.10.3, 10.10.45 String.format(…) 10.10.76 The StringBuilder Class 10.11

To make this document easier to read, it is recommend that you turn off spell checking in Word:

1. Choose: File, Option, Proofing2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…”

Stage 1 - One-to-One Association

In this stage we study a one-to-one association between classes.

1. (Read, no action required) Consider the class diagram shown on the right which shows that a Person has-a Dog. In UML this is indicated by the solid line between the two classes and is called an association (or a has-a relationship).

The role name, dog indicates that the Person class has an instance variable, dog of type Dog. The navigability is indicated by the arrow at the end of the association. Since the arrow points to Dog, this indicates that no only does a Person have a Dog, but a reference to the Dog can be obtained through the Person (via the getDog method shown below). The Person class indicated from the class diagram is:

public class Person {Dog dog;

public Dog getDog() {return dog;

}}

In the next few steps we will write the code indicated by the class diagram on the right.

2. Do the following:

a. Establish a Workspace – Create a folder on your drive where you will put your lab or use an existing one.

b. Run Eclipse – As the program begins to run, it will ask you to navigate to the Workspace you want to use.

1

Page 2: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

c. Create a Project – We will create the Project for Lab 2.

i. Choose: File, New, Java Project.ii. Supply a project name, lab02_lastNameFirstInitial, e.g. lab02_gibsond

iii. Choose: Finish

3. Add the Dog Class

a. Choose: File, New, Classb. Set the Package to “association1”c. Set the Name to “Dog”d. Choose: Finishe. Replace everything in the Dog class except the package statement at the top.

public class Dog {String name;

public Dog(String name) {this.name = name;

}

public String getName() {return name;

}

public String walk() {return name + " is walking";

}

public String barkAt(Dog d) {return name + " is barking at " + d.getName();

}

@Overridepublic String toString() {

return "dog named " + name;}

}

4. Add the Person Class – This will be the last time I give explicit instructions on creating a class.

a. Select the association1 node in the Package Explorer.b. Choose: File, New, Classc. Make sure the Package value is “association1”d. Set the Name to “Person”e. Choose: Finishf. Replace everything in the Person class except the package statement at the top.

public class Person {String name;Dog dog;

public Person(String name, Dog dog) {this.name = name;

2

Page 3: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

this.dog = dog;}

public String getName() {return name;

}

@Overridepublic String toString() {

return name + " has a " + dog;}

}

5. Add the Driver class – Repeat the previous steps using the code below:

public class Driver {

public static void main(String[] args) {Dog d = new Dog("Juno");Person p = new Person("Xavier", d);System.out.println(p);

}}

6. Run the code – This will be the last time we give explicit instructions for this. You can run your code in one of three ways:

a. Choose: Run, Run orb. Click the green arrow on the Toolbar orc. Press: Ctrl+F11

Make sure you understand exactly what the Person class and the Driver code are doing.

7. We will add a way for the Person to walk her dog. Notice that the Dog class has a walkDog method which returns a string:

public String walk() {return name + " is walking";

}

Do the following:

a. Add this method to the Person class after the constructor:

public String walkDog() {return name + " walks dog: " + dog.walk();

}

Notice that the method uses its reference, dog (to the Dog instance it contains) and calls the walk method. This is called delegation. The person is delegating to the dog’s walk method.

3

Page 4: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

b. Add this line to the end of main in Driver:

System.out.println(p.walkDog());

c. Run the code and observe the output.

8. We will add a way for the Person to provide a reference to its Dog. Do the following:

a. Add this method to the Person class after the walkDog method:

public Dog getDog() {return dog;

}

b. Add these lines to the end of main in Driver:

d = p.getDog();System.out.println(d.walk());

Notice that this code obtains a reference, d to the person’s dog and then we use it to tell the dog to walk.

c. Run the code and observe the output.

9. Consider the Dog class and its barkAt method which returns a string:

public String barkAt(Dog d) {return name + " is barking at " + d.getName();

}

Study the code carefully. Notice that the method accepts a reference to another Dog. Do the following:

a. Add these lines to the end of main in Driver:

Dog d2 = new Dog("Reily");System.out.println(d.barkAt(d2));

Notice that we create a new dog referenced by d2 which we pass to the barkAt method for d.

b. Run the code and observe the output.

4

Page 5: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

Stage 2 - One-to-One Association, Bi-directional Navigability

In this stage we study a one-to-one association between classes with navigability in both directions.

10. (Read, no action required) Consider the class diagram shown on the right which shows that a Person has-a Dog and shows navigability in both directions. In other words, the right arrow indications that if you have a Person, you can get her Dog. The left arrow indicates that if you have a Dog you can get its owner (Person).

11. Copy the association1 package and paste it giving the new name association2. (We could simply modify the code in association1 but here we will copy it to association2 and then modify it there so as to preserve the original).

12. Do the following:

a. Add a reference to the owner in the Dog class. Thus, add this instance variable to the Dog class:

Person owner;

b. Add a getter and a setter for the owner by adding this code to the Dog class:

public Person getOwner() {return owner;

}

public void setOwner(Person owner) {this.owner = owner;

}

c. Next, we need a way to assign a Person to be the owner of a Dog. One way is to use the Person’s constructor. Add this line to the end of the Person classes’ constructor:

this.dog.setOwner(this);

Note that this refers to the Person instance.

d. Replace the code in main for the Driver class with this code:

Dog d = new Dog("Juno");Person p = new Person("Xavier", d);d = p.getDog();Person p2 = d.getOwner();System.out.println(d.getName() + "'s owner is " + p2.getName() );

Study the code carefully.

e. Run and observe the output.

5

Page 6: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

Stage 3 - One-to-Many Association

In this stage we study a one-to-many association between classes.

13. (Read, no action required) Consider the class diagram shown on the right which shows that a Person has-many Dogs. The “*” in the class diagram indicates the multiplicity. In this case the multiplicity is “many” (technically, it means any number of Dogs, including 0).

Multiplicity in a class diagram indicates how many of one object (Dog) that another object possesses. For the example we code next (as shown on the right), we will use a multiplicity of “0..4” which means a Person can have up to 4 Dogs. We will implement the new Person class as we go along.

14. Copy the association1 package (not association2) and paste it giving the new name association3.

15. Do the following:

a. In the Person class, replace the instance variable:Dog dog;

With:Dog[] dogs = new Dog[4];

Thus, we will use an array to hold the Dogs. When you add this, you will see lots of compile errors. We will fix those as we go along.

b. We will need an instance variable to keep track of exactly how many Dogs a Person has. So, add this instance variable.

int numDogs = 0;

c. Add a getter for the number of Dogs:

public int getNumDogs() {return numDogs;

}

6

Page 7: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

d. Replace the constructor:public Person(String name, Dog dog) {

this.name = name;this.dog = dog;

}With:

public Person(String name) {this.name = name;

}

Thus, we will no longer supply a Dog when we create a Person. Instead, we will provide an addDog method in the next step.

e. Add this method to the Person class:

public void addDog(Dog d) {dogs[numDogs++] = d;

}

This method adds the dog, d to the dogs array and increments the number of dogs, numDogs.

f. Replace the code in the toString method with:

String msg = "";msg += name + " has " + numDogs + " dogs: ";for(int i=0; i<numDogs; i++) {

msg += dogs[i].getName() + ", ";}return msg;

Study this code carefully. Notice that we loop over the dogs array building a string with each dog’s name. The loop does not loop over the entire array (all 4 elements), it only loops over the actual number of dogs that have been added, numDogs. Make sure you see this.

g. Remove the walkDog and getDog methods. You shouldn’t see any compile errors now.

h. Replace the code in main for the Driver class with this code:

Person p = new Person("Xavier");Dog d = new Dog("Juno");p.addDog(d);d = new Dog("Zoro");p.addDog(d);d = new Dog("Leo");p.addDog(d);

System.out.println(p);

Study the code carefully.

i. Run and observe the output.

7

Page 8: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

16. Next, we provide a method that allows the Person to walk all her Dogs. Do the following:

a. Add this method to the Person class:

public String walkDogs() {String msg = "Dog's are walking...:\n";for(int i=0; i<numDogs; i++) {

msg += " " + dogs[i].walk() + "\n";}return msg;

}

Notice that the method loops over the actual number of Dogs and asks each Dog to walk.

b. Add the line below to the end of the code in main for the Driver class:

System.out.println(p.walkDogs());

c. Run and observe the output.

17. Next, we provide a way to get an individual Dog from its owner. Do the following:

a. Add this method to the Person class:

public Dog getDog(int i) {if(i>=0 && i<numDogs) {

return dogs[i];}return null;

}

Notice that the method accepts an index, i which is checked to make sure it is valid, e.g. 0≤ i<numDogs. If the index is valid, then it returns the corresponding Dog.

b. Add the lines below to the end of the code in main for the Driver class:

Dog d2 = p.getDog(1);System.out.println(d2);

c. Run and observe the output.

8

Page 9: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

18. Now, let’s provide a new constructor in the Person class that allows a user to supply an array of Dogs when the Person is created. Do the following:

a. Add this constructor to the Person class just below the existing constructor:

public Person(String name, Dog[] dogs) {this(name);for(Dog d : dogs) {

addDog(d);}

}

Notice that we loop over all the dogs in the input array, dogs and add each one to the Person’s dogs array using the addDog method. Notice also that this code is dangerous because someone could pass in an array that has more than 4 dogs.

b. Add the lines below to the end of the code in main for the Driver class:

Dog[] dogs = new Dog[] { new Dog("Gigi"), new Dog("Spot") };Person p2 = new Person("Liz", dogs);System.out.println(p2);p2.addDog(new Dog("Delila"));System.out.println(p2);

c. Run and observe the output. Study the code above carefully and correlate with the output.

19. Finally, we provide a way to lose a dog (i.e. remove a dog). Do the following:

a. Add this method to the Person class:

public void loseDog(int i) {if(i>=0 && i<numDogs) {

for(int j=i; j<numDogs-1; j++) {dogs[j] = dogs[j+1];

}numDogs--;

}}

Study this code carefully! We don’t actually “delete” the Dog at position i. We simply shift all the Dogs to the right of it to the left one position. For example, suppose a Person’s dogs array is:

numDogs = 4

element

Gigi Spot Waldo Snoopy

index 0 1 2 3

9

Page 10: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

Next, suppose the method is called with i=1, loseDog(1). Then the array becomes:

numDogs = 3

element

Gigi Waldo Snoopy

index 0 1 2 3

Actually, “Snoopy” is also in the last position, but our counter, numDogs has been decremented to 3 so that we do not “see” that last position.

b. Add the method below to the Driver class:

public static void testLoseDog() {System.out.println("testLoseDog()");Dog[] dogs = new Dog[] { new Dog("Gigi"), new Dog("Spot"), new

Dog("Waldo") };Person p2 = new Person("Liz", dogs);System.out.println(p2);p2.loseDog(0);System.out.println(p2);

p2.addDog(new Dog("Goofy"));System.out.println(p2);p2.loseDog(1);System.out.println(p2);p2.loseDog(1);System.out.println(p2);

}

c. Add the lines below to the end of the code in main for the Driver class:

Dog[] dogs = new Dog[] { new Dog("Gigi"), new Dog("Spot") };Person p2 = new Person("Liz", dogs);System.out.println(p2);p2.addDog(new Dog("Delila"));System.out.println(p2);

testLoseDog();

d. Run and observe the output. Study the code above carefully and correlate with the output.

10

Page 11: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

Stage 4 - String.split(…)

In this stage we consider an example of parsing a string using the String.split(delimiter). We don’t go in depth here, we just show a few examples.

20. (Read, no action required). Suppose you have a string of numbers separated by commas:

String data = "4.8,3.9,22.6,7.1";

If you use the split method on this data using the “,” delimiter:

String[] strNums = data.split(",");

The result will be a string array of the numbers:

element

“4.8” “3.9” “22.6” “7.1”

index 0 1 2 3

If you want to use more than one delimiter, you enclose them in brackets. For example, suppose you have a string with numbers separated by either a comma or a colon, then these statements:

String data2 = "4.8,3.9:22.6:7.1";String[] strNums2 = data2.split("[,:]");

Would produce the same array as above. You can split on a space. For example, this code:

String data3 = "4.8 3.9 22.6 7.1";String[] strNums3 = data3.split(" ");

Would again produce the same array as above. This approach is a bit limited. For example, if you had 2 spaces between a pair of numbers (4.8 and 3.9):

String data4 = "4.8 3.9 22.6 7.1";String[] strNums4 = data4.split(" ");

Would produce the array, strNums4 with these values:

“4.8” “” “3.9” “22.6” “7.1”0 1 2 3 4

In other words, the element at index 1 is an empty string. To split on 1 or more spaces, you should use a regular expression. We will consider these very briefly, though your text goes into a little more detail. For example:

String data5 = "4.8 3.9 22.6 7.1";String[] strNums5 = data5.split("\\s+");

Produces the array shown previously with just the four (string) numbers: “4.8”, “3.9”, “22.6”, “7.1”. In the highlighted expression above, the “\s” represents a single space, the “+” means “a space or more”, and finally, an additional slash is needed at the beginning so that Java interprets it correctly.

11

Page 12: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

You can specify 2 or more patterns by putting “|” between the patterns. For example, to split on “1 or more spaces” (\\s+) or “a comma followed by zero or more spaces” (,\\s*), we would use the delimiter highlighted in yellow below:

String data6 = "4.8,3.9 22.6, 7.1";String[] strNums6 = data6.split("\\s+|,\\s*");

Where the “*” means, “zero or more”.

21. Add a new class

a. Select the src folder.b. Choose: File, New, Classc. Set the Package to “string_examples”d. Set the Name to “StringExamples”e. Select the box to generate main.f. Choose: Finish

22. We will write an example that breaks a string of sentences into individual sentences based on sentences being separated by a period followed by zero or more spaces (“\\.\\s*”), or an exclamation (“\\!\\s*”), or question (“\\?\\s*”). Do the following:

a. Add this method to the StringExamples class:

public static void testSplitSentences() {System.out.println("testSplitSentences()");Scanner keyboard = new Scanner(System.in);System.out.println("Enter a few sentences with common punctuation");String text = keyboard.nextLine();

int count = 1;String[] sentences = text.split("\\.\\s*|\\!\\s*|\\?\\s*");for(String sentence : sentences) {

System.out.println("Sentence " + (count++) + ":\"" + sentence + "\"" );

}System.out.println();keyboard.close();

}

b. Add this line to main to call the method:

testSplitSentences();

c. Run the code and paste this sentence:

This is big, really big; or not. Know what I mean? Yes:I do know. Really cool! Now’s the time.

d. Study the code carefully and correlate with the output. Run the code again and experiment with your own sentences. You can probably break it!

12

Page 13: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

23. We will write a similar example as the previous one that splits a string of sentences into individual words. In addition to the delimiters used above, we will also need to specify spaces, commas, semi-colons, and colons. Do the following:

a. Add this method to the StringExamples class:

public static void testSplitWords() {System.out.println("testSplitWords()");Scanner keyboard = new Scanner(System.in);System.out.println("Enter a few sentences with common punctuation");String text = keyboard.nextLine();

String[] words = text.split("\\s+|\\,\\s*|\\;\\s*|\\:\\s*|\\.\\s*|\\!\\s*|\\?\\s*");

System.out.print("Words:");for(String word : words) {

System.out.print("\"" + word + "\", " );}System.out.println();keyboard.close();

}

b. Add this line to main to call the method:

testSplitWords();

c. Comment out the call to testSplitSentences.

d. Run the code and paste this sentence:

This is big, really big; or not. Know what I mean? Yes:I do know. Really cool! Now’s the time.

e. Study the code carefully and correlate with the output. Run the code again and experiment with your own sentences. You can probably break it!

Stage 5 - String.format(…)

In this stage we consider formatting strings.

24. Do the following:

a. Add this method to the StringExamples class:

public static void testStringFormat(){System.out.println("testStringFormat()");

double y = 32914.4380239;String msg = String.format("y = %.2f", y);System.out.println(msg);

}

13

Page 14: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

b. Add this line to main to call the method:

testStringFormat();

c. Comment out the call to testSplitWords.

d. Run the code and observe the output.

e. (Read, no action required). The String class has a static format method that is used to create formatted strings. For example, examine the line from above:

String.format("y = %.2f", y);

from the example above. The yellow highlighted portion is a string literal; which will be placed in the new, returned string exactly as written. Next, we see, “%.2f” which is a format specifier. It means that the next variable (in this case y) will have its value placed in the return string in this location formatted with 2 decimals. Now, let’s summarize:

i. “%” is always used to start a format specifier.ii. “.2” is optional but denotes that we want 2 decimals.

iii. “f” is used to indicate a floating point number.

The general syntax is:

String.format( format, val1, val2, …)

where “format” is a string composed of string literals and format specifiers (green highlight above).

f. Change the “.2” to “.3” or some other value, run, and observe the results.

g. Change the “.2” (or whatever you last used) to “,.2”, run, and observe the results. Note the “,” that precedes the “.”; this indicates to use a “,” for the thousands separator.

h. Change the entire format to: "y = $%,.3f\n", run, and observe the results. Note the “$” is a string literal and precedes the format specifier.

i. Add these lines to the end of the testStringFormat method:

int z = 484;String s = "these are numbers";

msg = String.format("y = %,.2f, z = %d, %s", y, z, s);System.out.println(msg);

Note that “%d” format specifier is used for integers and “%s” for strings.

j. Run and observe the output.

14

Page 15: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

25. Java defines a printf method that very similar to String.format. It is a “formatted print” with the same arguments as String.format. However, it does not produce line feed (e.g. it is like print as opposed to println). Thus, if we want a line feed, we add “\n”. Add this line to the end of the testStringFormat method, run, and observe the output:

System.out.printf("y = %,.2f, z = %d, %s\n", y, z, s);

Stage 6 - The StringBuilder Class

In this stage we consider the StringBuilder class.

26. The StringBuilder class is a more efficient and enhanced String class. Do the following:

a. Add this method to the StringExamples class:

public static void testStringBuilder(){StringBuilder sb = new StringBuilder("This is ");sb.append("a sentence.");System.out.println(sb.toString());

}

b. Add this line to main to call the method:

testStringBuilder();

c. Comment out the call to any other method calls in main.

d. Run the code and observe the output.

e. (Read, no action required). As the text discusses, and we discuss in class, a String object is immutable; it cannot be changed. Recall that String methods such as replace and substring return a new string; they don’t modify the string they are operating on. The StringBuilder class has essentially the same methods as the String class and many more; however, they do modify the internal string that they hold which makes it more efficient in cases where we need to modify a string.

In the example above we use the append method to add a new string onto the end of the existing string. The StringBuilder class has many more methods, for example: delete, insert, replace, substring, toString, and others.

15

Page 16: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

27. If you need to build a string from an arbitrary number of values you should use StringBuilder as opposed to concatenating Strings as it is much more efficient, especially when the number of values can be large. Next, we will do an experiment to compare using StringBuilder and String concatenation to build a large string. Do the following:

a. Add this method to the StringExamples class:

public static void testStringBuilderEfficiency() {int size = 25000;double[] vals = buildRandomDoubleArray(size);String doubleString1 = testStringConcat(vals);String doubleString2 = testStringBuilderConcat(vals);

}

(Read, no action required). This method calls three methods that we will add in just a minute. This method calls buildRandomDoubleArray to build an array of 25,000 random doubles. Next, it passes the array to a method that builds one giant string with all the values concatenated together with a comma between using String concatenation. For example (vals contains the 25,000 doubles):

String doublesString = "";for(double d : vals) {

doublesString += d + ", ";}

We time this method and display the length in seconds. Next, we pass this same array of doubles to another method that uses StringBuilder to build the string with code like this:

StringBuilder doublesString = new StringBuilder();for(double d : vals) {

doublesString.append(d + ", ");}

Again, we time this method and display the length in seconds. You will be surprised at the results.

b. Add these methods to the StringExamples class:

public static double[] buildRandomDoubleArray(int size) {double[] vals = new double[size];for( int i=0; i<vals.length; i++ ) {

vals[i] = Math.random()*1000.0;}return vals;

}

public static String testStringConcat(double[] vals) {System.out.println("testStringConcat()");

long begTime = System.currentTimeMillis();String doublesString = "";for(double d : vals) {

doublesString += d + ", ";}long endTime = System.currentTimeMillis();

double totTime = (endTime-begTime)/1000.0;

16

Page 17: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewString . and . StringBuilder . ... To make this document easier to read, it is recommend that

String msg = String.format(" Concatenate %,d doubles = %.3f sec", vals.length, totTime);

System.out.println(msg);return doublesString;

}

public static String testStringBuilderConcat(double[] vals) {System.out.println("testStringBuilderConcat()");

long begTime = System.currentTimeMillis();StringBuilder doublesString = new StringBuilder();for(double d : vals) {

doublesString.append(d + ", ");}long endTime = System.currentTimeMillis();

double totTime = (endTime-begTime)/1000.0; String msg = String.format(" Concatenate %,d doubles = %.3f sec",

vals.length, totTime); System.out.println(msg);

return doublesString.toString();}

c. Add this line to main to call the method:

testStringBuilderEfficiency();

d. Comment out the call to any other method calls in main.

e. Run the code and observe the output.

f. Change 25000 to 30000 in testStringBuilderEfficiency and you will see the time almost double!

You are done!

17


Recommended