//利用搜索引擎实现命令行计算器
import java.io.*;
import java.net.*;
/**
* 54powerman
* http://54powerman.blog.sohu.com
**/
public class Cal
{
final static String defaultCharset=System.getProperty("file.encoding");
public static void main(String args[])
{
String express=null;
if(args.length<1)
{
System.out.println("[Usage]: java Cal [expressions]");
return;
}
express=args[0].trim();
String url=null;
try{
url="http://www.baidu.com/s?wd="+java.net.URLEncoder.encode(express,defaultCharset)+"&cl=3";
}
catch(UnsupportedEncodingException e){}
String result=OpenUrl(url,"");
int start=result.indexOf("http://img.baidu.com/img/jsq.gif");
if(start>0){
int end=0;
start=result.indexOf("<b>"+express,start);
start=result.indexOf("=",start)+1;
end=result.indexOf("</b>",start);
result=result.substring(start,end).trim();
}
if(result.indexOf("/n")>0)
{
System.out.println("express error.");
}
else
{
System.out.print(result);
}
}
public static String OpenUrl(String urlString,String postParam) {
StringBuffer document = new StringBuffer();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!postParam.trim().equals("")){
conn.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), defaultCharset);
out.write(postParam);
out.flush();
out.close();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ( (line = reader.readLine()) != null) {
document.append(line + "/n");
}
reader.close();
}
catch (MalformedURLException e) {
System.out.println("Unable to connect to URL: " + urlString);
}
catch (IOException e) {
System.out.println("IOException when connecting to URL: " + urlString);
}
return document.toString();
}
}