?? currencyexchange.java
字號(hào):
package ch09.section04;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class CurrencyExchange
extends MIDlet
implements CommandListener {
//退出按鈕
private Command exitCommand;
private Display display;
Form displayForm;
public CurrencyExchange() {
display = Display.getDisplay(this);
exitCommand =
new Command("Exit", Command.SCREEN, 1);
}
//啟動(dòng)應(yīng)用程序,創(chuàng)建窗體,打開(kāi)連接
public void startApp() {
displayForm = new Form("Exchange Rate");
displayForm.addCommand(exitCommand);
displayForm.setCommandListener(this);
try {
String result = getViaHttpConnection
("http://finance.yahoo.com/m5?a=1&s=USD&t=GBP");
displayForm.append(" " + result);
}
catch (Exception exc) {
exc.printStackTrace();
}
display.setCurrent(displayForm);
}
//掛起應(yīng)用程序
public void pauseApp() {}
//銷(xiāo)毀應(yīng)用程序
public void destroyApp(boolean unconditional) {}
//響應(yīng)退出按鈕事件
public void commandAction(
Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
String parse(String str) {
//獲取相關(guān)金融信息
int timeIndex = str.indexOf("U.S. Markets Closed.");
String retTime = "";
if (timeIndex != -1) {
retTime = str.substring(timeIndex - 34, timeIndex);
retTime += " U.S. Markets Closed ";
}
String retVal = "";
int dec = 0;
int index = str.indexOf("USDGBP");
if (index != -1) {
str = str.substring(index, str.length());
}
if ( ( (dec = str.indexOf(".")) != -1) && (! (str.endsWith(".")))
&& Character.isDigit(str.charAt(dec + 1))) {
String front = "";
int find = dec - 1;
while (Character.isDigit(str.charAt(find))) {
front += str.charAt(find);
find--;
}
retVal += new StringBuffer(front).reverse().toString();
retVal += ".";
String back = "";
int bind = dec + 4;
while (Character.isDigit(str.charAt(bind))) {
back += str.charAt(bind);
bind--;
}
retVal += new StringBuffer(back).reverse().toString();
}
System.out.println(retVal);
return "USD/GBP " + retVal + " at " + retTime;
}
String getViaHttpConnection(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
StringBuffer str = new StringBuffer();
try {
c = (HttpConnection) Connector.open(url);
//獲取當(dāng)前內(nèi)容類(lèi)型
String type = c.getType();
// requested.打開(kāi)輸入流,用于讀取HTTP頭
is = c.openInputStream();
//獲取信息長(zhǎng)度
int len = (int) c.getLength();
int ch;
while ( (ch = is.read()) != -1) {
str.append( (char) ch);
}
}
finally {
if (is != null) {
is.close();
}
if (c != null) {
c.close();
}
}
//解析字符串,獲取匯率
String val = parse(str.toString());
System.out.println(val);
return val;
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -