|
Lesson SevenAdvanced array techniques | |
Arrays can be very useful when it comes to sorting. If you are sorting from the lowest value to the highest, you are sorting in ascending order. If you are sorting the highest value to the lowest, you are sorting in descending order. Another sorting method called bubble sort sorts an unsorted array by swapping values until they are from lowest to highest. For instance, the values 88, 33, 99, 22, 54 will be swapped until they read 22, 33 54, 88, 99. Below is a program showing how bubble sorting works. Characters and numbers are a simple form of sorting. You can also sort Strings. One important point to remember with Strings is that the names are memory addresses. In this sense, you must use the compareTo() method. As you may have noticed, these arrays print in the form of a single column. These are called single-dimensional arrays. To achieve the effect of a table, you need more than one column. This is what we call a two-dimensional array (also known as a matrix or a spreadsheet). The way you create a two-dimensional array is: One problem with Strings is that you cannot have myName = "John" and myName = "Smith" at the same time. One thing you can do is use the StringBuffer to join two strings. If you typed StringBuffer myName = new StringBuffer("John");, and then typed myName.append(" Smith");, you'd end up with the String "John Smith". The append() method adds a String to a String similar to the way concatenation works. Along with these methods is the insert() that you can use to insert a String. For instance, if you wanted to add your middle name to the String. You would then type myName.insert(5, "Alexander ");. Seeing as Strings work the same way as arrays, the letter "J" in John is in the [0] position of the entire String. The number "5" means go to the [5] element and insert "Alexander". If you just wanted to add "A", you would type myName.setCharAt(5, "A"); instead of the insert() method. Then, put a space inside the parenthesis after John. If you're not too sure about what you've learned so far, or if you seem to be having problems in the future, there are some newsgroups you can attend: If you can't find the answer you're looking for at any sites, you can always take a look at Frequently Asked Questions or the Help file at the Sun Microsystems Web site. |
|
Question: Ok, I've learned a great deal coming here. The only thing I want to know is how I can apply all this knowledge to my Web page. Is there a way? Answer: Well, I'm glad to hear that you've learned something besides patience. Now, to be able to transfer what you've learned to the Internet, you need to create an applet. | |
If you have a questions about any of the lessons, feel free to ask. |