刚开始学java,在一本书遇到两个小程序,需要高手指点一下:第一个:
模拟电梯程序。要求:
(1)界面左边从下到上画10个方格,代表10层楼。此时某个方格内有个图标,表示电梯现在的位置。
(2)右边放10个按钮,表示要去的楼层。
(3)点击某个按钮(表示人现在所在的楼层),如果电梯此时和人不再用一楼层,电梯(图标)移到该层,停顿3秒;
(4)再点击要到的楼层按钮,电梯移动到该层,停止,等待下次用户选择;
第二个:
编写一个网络程序,实现网页搜索功能。要求:
(1)用户先输入一个关心的字符串,如:软件下载;
(2)再输入要查找的网页,点击查找按钮;
(3)程序读取网页内容,如果发现其中有要被查找的字符串,则将此网页保存到本地,否则提示用户没找到;
模拟电梯程序。要求:
(1)界面左边从下到上画10个方格,代表10层楼。此时某个方格内有个图标,表示电梯现在的位置。
(2)右边放10个按钮,表示要去的楼层。
(3)点击某个按钮(表示人现在所在的楼层),如果电梯此时和人不再用一楼层,电梯(图标)移到该层,停顿3秒;
(4)再点击要到的楼层按钮,电梯移动到该层,停止,等待下次用户选择;
第二个:
编写一个网络程序,实现网页搜索功能。要求:
(1)用户先输入一个关心的字符串,如:软件下载;
(2)再输入要查找的网页,点击查找按钮;
(3)程序读取网页内容,如果发现其中有要被查找的字符串,则将此网页保存到本地,否则提示用户没找到;
编写一个网络程序,实现网页搜索功能。要求:
(1)用户先输入一个关心的字符串,如:软件下载;
(2)再输入要查找的网页,点击查找按钮;
(3)程序读取网页内容,如果发现其中有要被查找的字符串,则将此网页保存到本地,否则提示用户没找到;
如果要做GUI界面稍微麻烦一点,思路:import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;public class URLCon { /**
* @param args
*/
public static void main(String[] args) { URL u;
try {
u = new URL("http://www.sohu.com");
URLConnection ucon=u.openConnection();
InputStream is=ucon.getInputStream();
byte []buf=new byte[1024];
while(is.read()!=-1){
int length=is.read(buf);
String result=new String(buf,0,length);
System.out.println(result);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}}
//字符串的搜索可以看String类,如果找到可以把取得的流写到文件,不写了
思路:public class mySearch{
private String keyword = null;
private String targetUrl = null;
public mySearch(String keyword, Stirng url){
this.keyword = keyword;
this.targetUrl = url;
} public search(){
String pageContent = httpGet(this.targetUrl);
if(pageContent.indexOf(this.keyword) != -1){
//找到符合的网页, 保存
}else{
//没找到, 提示错误
}
}
private void info(String msg)){
System.out.println("INFO - "+msg);
} private void warn(String msg){
System.out.println("WARN - "+msg);
}
private void error(Exception ex, String msg){
System.error.println("ERROR - "+ex+";"+msg);
}
private void error(String msg)){
System.out.println("ERROR - "+msg);
} private String httpGet(String strURL){
String retString = "";
HttpURLConnection httpUrl = null;
try {
URLConnection url = (new URL(strURL)).openConnection();
httpUrl = (HttpURLConnection) url;
httpUrl.setAllowUserInteraction(true);
if (httpUrl.getResponseCode() != HttpURLConnection.HTTP_OK) {
warn("http get request error, http status:["+httpUrl.getResponseCode()+"], remote host may not be available:" + strURL);
}else{
BufferedReader rd = new BufferedReader(new InputStreamReader(httpUrl.getInputStream()));
StringBuffer sb = new StringBuffer();
int ch;
while ( (ch = rd.read()) > -1)
sb.append( (char) ch);
retString = sb.toString();
rd.close();
}
}
catch (MalformedURLException ex) {
error(ex, "open url :" + strURL);
}
catch (IOException ex) {
error(ex, "open url :" + strURL);
}
catch (Exception ex) {
error(ex, "open url :" + strURL);
} finally {
httpUrl.disconnect();
}
return retString;
}
}