Sekarang, kita akan membuat aplikasi sederhana untuk memisahkan string, seperti pada gambar di bawah ini:
Mau tau sintaksnya? ini dia.....
import java.util.Vector; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextField; import javax.microedition.midlet.*; /** * @author Dyah Fajar * 6 Oct 2010 16:23 */ public class SplitMidlet extends MIDlet implements CommandListener{ private Display dsp; private Form frm; private TextField txt1; private TextField txt2; private StringItem str; private Command cmdSplit; private String[] hasil; public SplitMidlet() { dsp = Display.getDisplay(this); frm = new Form("Form"); txt1 = new TextField("String", "", 100, TextField.ANY); txt2 = new TextField("Delimeter/Separator", "", 1, TextField.ANY); str = new StringItem("hasil\n", ""); cmdSplit = new Command("Split", Command.OK, 0); frm.addCommand(cmdSplit); frm.append(txt1); frm.append(txt2); frm.append(str); frm.setCommandListener(this); } public void startApp() { dsp.setCurrent(frm); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { if (c == cmdSplit){ String semua = ""; hasil = split(txt1.getString(), txt2.getString()); for (int i =0; i<hasil.length; i++){ semua = semua + hasil[i] +"\n"; } str.setText(semua); } } private String[] split(String original, String s){ Vector nodes = new Vector(); String separator = s; System.out.println("split start..................."); // Parse nodes into vector int index = original.indexOf(separator); while (index >= 0) { nodes.addElement(original.substring(0, index)); original = original.substring(index + separator.length()); index = original.indexOf(separator); } nodes.addElement(original); // Create splitted string array String[] result = new String[nodes.size()]; if (nodes.size() > 0) { for (int loop = 0; loop < nodes.size(); loop++) { result[loop] = (String) nodes.elementAt(loop); System.out.println(result[loop]); } } return result; } } |
Komentar
Posting Komentar
Terima kasih sudah membaca....^^