Casting a String to a Character Array
Introduction.
Back when we were working with switch code segments I needed to make use
of arrays in order to turn a
user's string input into a character for a switch. I want to
revisit that program a bit to make certain you understand why we based the
switch on element choice[0] in the character array. The next program will illustrate a few things we have worked with so far this semester in terms of llops, built-in methods of strings and characters, arrays and displaying output. This application should be called StringToArray.java. |
import javax.swing.JOptionPane; import javax.swing.JTextArea; public class StringToArray {
} |
I ran the program with the following input string. |
This resulted in the following output. |
Code Discussion. We will use our usual outline form to discuss the code.
You can play with this all you want. It provides another example of working with arrays. It should also help make more sense of the earlier code for getting user inputs into a useful form in order to get a switch code segment to work. You should now be able to think of other ways to get this to work by using some sort of built-in string method to grab the first character or the user's input and assigning it to a character for switching. |