diff --git a/.gitignore b/.gitignore index aa8aa0253e..03eb89aed0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,267 @@ +################# +## Eclipse +################# +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml +*.publishproj + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[cod] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg +.gitignore +======= + + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#ide config +.metadata +.recommenders + + +*.xml +*.iml +.idea +*.iml +rebel.xml +rebel-remote.xml + +.classpath +.project +.setting +.metadata + +target +*.class + +log +*.log +tmp +*.tmp + +.metadata +RemoteSystemsTempFiles +.gitignore + + +build/ +.idea/ +.gradle/ *.class # Mobile Tools for Java (J2ME) .mtj.tmp/ @@ -20,9 +283,6 @@ rebel.* .rebel.* target - -#bin/ -#.setting/ -#*.classpath -#*.project - +*.DS_Store +liuxin/.DS_Store +liuxin/src/.DS_Store diff --git a/.gitignore.bak b/.gitignore.bak new file mode 100644 index 0000000000..bfc52534d9 --- /dev/null +++ b/.gitignore.bak @@ -0,0 +1,301 @@ +<<<<<<< HEAD + +======= +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml +*.publishproj + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[cod] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg +.gitignore +======= + + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#ide config +.metadata +.recommenders + + +*.xml +*.iml +.idea +*.iml +rebel.xml +rebel-remote.xml + +.classpath +.project +.setting +.metadata + +target +*.class + +log +*.log +tmp +*.tmp + +.metadata +RemoteSystemsTempFiles +.gitignore + + +build/ +.idea/ +.gradle/ +>>>>>>> 9480ef8682c393444f53a282b34e23a087ef73e6 +*.class +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#ide config +.metadata +.recommenders +.idea/ +*.iml +rebel.* +.rebel.* + +target +<<<<<<< HEAD + +#bin/ +#.setting/ +#*.classpath +#*.project +======= +*.DS_Store +liuxin/.DS_Store +liuxin/src/.DS_Store +>>>>>>> 9480ef8682c393444f53a282b34e23a087ef73e6 + diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/DownloadThread.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..79cb9d5246 --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/DownloadThread.java @@ -0,0 +1,37 @@ +package com.github.FelixCJF.coding2017.coderising.download; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +import com.github.FelixCJF.coding2017.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + System.out.println("下载开始"); + try { + byte[] buff = conn.read(startPos, endPos); + //创建一个可随机写入文件 + RandomAccessFile randomAccessFile = new RandomAccessFile(new File("G:/"), "rwd"); + randomAccessFile.seek(startPos); + randomAccessFile.write(buff, 0, buff.length); + randomAccessFile.close(); + + System.out.println("下载结束"); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloader.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..f9d79fcae4 --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloader.java @@ -0,0 +1,87 @@ +package com.github.FelixCJF.coding2017.coderising.download; + +import com.github.FelixCJF.coding2017.coderising.download.api.Connection; +import com.github.FelixCJF.coding2017.coderising.download.api.ConnectionException; +import com.github.FelixCJF.coding2017.coderising.download.api.ConnectionManager; +import com.github.FelixCJF.coding2017.coderising.download.api.DownloadListener; + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + int length = conn.getContentLength(); + //自定义线程数量 + int threadCount = 3; + //计算每条线程下载数据的大小 + int blockSize = length/threadCount; + + for (int threadId = 0; threadId <= threadCount; threadCount++) { + + //定义每个线程开始以及结束的下载位置 + // 开始下载的位置 + int startPos = (threadId - 1) * blockSize; + // 结束下载的位置(不包含最后一块) + int endPos = (threadId * blockSize) - 1; + if (threadCount == threadId) { + endPos = length; + } + new DownloadThread(conn,0,length-1).start(); + } + + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloaderTest.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4e96a56459 --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/FileDownloaderTest.java @@ -0,0 +1,60 @@ +package com.github.FelixCJF.coding2017.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.github.FelixCJF.coding2017.coderising.download.api.ConnectionManager; +import com.github.FelixCJF.coding2017.coderising.download.api.DownloadListener; +import com.github.FelixCJF.coding2017.coderising.download.impl.ConnectionManagerImpl; + + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "https://www.baidu.com/img/bd_logo.png"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/Connection.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/Connection.java new file mode 100644 index 0000000000..e4469d666f --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.github.FelixCJF.coding2017.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionException.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..657ba9543e --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.github.FelixCJF.coding2017.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionManager.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..f131cb622b --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.github.FelixCJF.coding2017.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/DownloadListener.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..a14e84acb4 --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.github.FelixCJF.coding2017.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionImpl.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..b56384022e --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,54 @@ +package com.github.FelixCJF.coding2017.coderising.download.impl; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URLConnection; + +import com.github.FelixCJF.coding2017.coderising.download.api.Connection; + + +public class ConnectionImpl implements Connection{ + + + public URLConnection urlConnection; + + public ConnectionImpl(URLConnection urlConnection) { + this.urlConnection = urlConnection; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + //设置连接超时属性 + urlConnection.setReadTimeout(5000); + + urlConnection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + + BufferedInputStream inputStream= new BufferedInputStream(urlConnection.getInputStream()); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + byte[] buff = new byte[1024]; + int len = 0; + + while ((len = inputStream.read(buff)) != -1) { + outputStream.write(buff,0,len); + } + byte[] temp = outputStream.toByteArray(); + + inputStream.close(); + outputStream.close(); + + return temp; + } + + @Override + public int getContentLength() { + return urlConnection.getContentLength(); + } + + @Override + public void close() { + urlConnection = null; + } + +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionManagerImpl.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..771dd30b36 --- /dev/null +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,25 @@ +package com.github.FelixCJF.coding2017.coderising.download.impl; + + +import java.net.URL; + +import com.github.FelixCJF.coding2017.coderising.download.api.Connection; +import com.github.FelixCJF.coding2017.coderising.download.api.ConnectionException; +import com.github.FelixCJF.coding2017.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + Connection connection = null; + try { + + connection = new ConnectionImpl(new URL(url).openConnection()); + + } catch (Exception e) { + e.printStackTrace(); + } + return connection; + } + +} diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/LoginAction.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/LoginAction.java index dcdbe226ed..b803afb24d 100644 --- a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/LoginAction.java +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/LoginAction.java @@ -1,39 +1,43 @@ -package com.coderising.litestruts; - -/** - * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 - * @author liuxin - * - */ -public class LoginAction{ - private String name ; - private String password; - private String message; - - public String getName() { - return name; - } - - public String getPassword() { - return password; - } - - public String execute(){ - if("test".equals(name) && "1234".equals(password)){ - this.message = "login successful"; - return "success"; - } - this.message = "login failed,please check your user/pwd"; - return "fail"; - } - - public void setName(String name){ - this.name = name; - } - public void setPassword(String password){ - this.password = password; - } - public String getMessage(){ - return this.message; - } -} +package com.github.FelixCJF.coding2017.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/Struts.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/Struts.java index 85e2e22de3..32852a36dd 100644 --- a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/Struts.java +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/Struts.java @@ -1,34 +1,84 @@ -package com.coderising.litestruts; - -import java.util.Map; - - - -public class Struts { - - public static View runAction(String actionName, Map parameters) { - - /* - - 0. 读取配置文件struts.xml - - 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) - 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 - ("name"="test" , "password"="1234") , - 那就应该调用 setName和setPassword方法 - - 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" - - 3. 通过反射找到对象的所有getter方法(例如 getMessage), - 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , - 放到View对象的parameters - - 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, - 放到View对象的jsp字段中。 - - */ - - return null; - } - -} +package com.github.FelixCJF.coding2017.coderising.litestruts; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + View view = new View(); + + try { + // 0. 读取配置文件struts.xml + //0.1将xml加载进内存中 + SAXReader reader = new SAXReader(); + Document document = null; + try{ + document = reader.read("src/com/github/FelixCJF/coding2017/coderising/litestruts/struts.xml"); + }catch (Exception e) { + e.printStackTrace(); + } + //0.2读取根元素 + Element rootElement = document.getRootElement(); + //0.3根据根元素获取其子元素 + List actionElements = rootElement.elements("action"); + for (int i = 0; i < actionElements.size(); i++) { + Element actionElement = actionElements.get(i); + if (actionName.equals(actionElement.attributeValue("name"))) { + // 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + String className = actionElement.attributeValue("class"); + Class clazz = Class.forName(className); + Object object = clazz.newInstance(); + // 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + // ("name"="test" , "password"="1234") , + // 那就应该调用 setName和setPassword方法 + for (Map.Entry entry : parameters.entrySet()) { + PropertyDescriptor descriptor = new PropertyDescriptor(entry.getKey(), clazz); + Method method = descriptor.getWriteMethod(); + method.invoke(object, entry.getValue()); + } + // 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + Method execute = clazz.getMethod("execute"); + String result = (String) execute.invoke(object); + // 3. 通过反射找到对象的所有getter方法(例如 getMessage), + // 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + Field[] fields = clazz.getDeclaredFields(); + HashMap map = new HashMap<>(); + for (Field field : fields) { + PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz); + Method method = descriptor.getReadMethod(); + Object value = method.invoke(object); + map.put(field.getName(), value); + } + // 放到View对象的parameters + view.setParameters(map); + // 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + // 放到View对象的jsp字段中。 + List resultElements = actionElement.elements("result"); + for (int j = 0; j < resultElements.size(); j++) { + Element resultElement = resultElements.get(j); + if (result.equals(resultElement.attributeValue("name"))) { + view.setJsp(resultElement.getText()); + return view; + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/StrutsTest.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/StrutsTest.java index b8c81faf3c..1157313180 100644 --- a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/StrutsTest.java +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/StrutsTest.java @@ -1,43 +1,43 @@ -package com.coderising.litestruts; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - - - - - -public class StrutsTest { - - @Test - public void testLoginActionSuccess() { - - String actionName = "login"; - - Map params = new HashMap(); - params.put("name","test"); - params.put("password","1234"); - - - View view = Struts.runAction(actionName,params); - - Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); - Assert.assertEquals("login successful", view.getParameters().get("message")); - } - - @Test - public void testLoginActionFailed() { - String actionName = "login"; - Map params = new HashMap(); - params.put("name","test"); - params.put("password","123456"); //密码和预设的不一致 - - View view = Struts.runAction(actionName,params); - - Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); - Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); - } -} +package com.github.FelixCJF.coding2017.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} \ No newline at end of file diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/View.java b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/View.java index 07df2a5dab..6d74cb6843 100644 --- a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/View.java +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/View.java @@ -1,23 +1,23 @@ -package com.coderising.litestruts; - -import java.util.Map; - -public class View { - private String jsp; - private Map parameters; - - public String getJsp() { - return jsp; - } - public View setJsp(String jsp) { - this.jsp = jsp; - return this; - } - public Map getParameters() { - return parameters; - } - public View setParameters(Map parameters) { - this.parameters = parameters; - return this; - } -} +package com.github.FelixCJF.coding2017.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} \ No newline at end of file diff --git a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/struts.xml b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/struts.xml index a6cfe43e6c..8a5fe95942 100644 --- a/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/struts.xml +++ b/group02/1554421063/src/com/github/FelixCJF/coding2017/coderising/litestruts/struts.xml @@ -1,11 +1,11 @@ - - - - /jsp/homepage.jsp - /jsp/showLogin.jsp - - - /jsp/welcome.jsp - /jsp/error.jsp - + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + \ No newline at end of file diff --git a/group02/562768642/src/com/github/orajavac/coding2017/basic/LinkedList.java b/group02/562768642/src/com/github/orajavac/coding2017/basic/LinkedList.java index 3cc762aeff..ec8fd7a4a7 100644 --- a/group02/562768642/src/com/github/orajavac/coding2017/basic/LinkedList.java +++ b/group02/562768642/src/com/github/orajavac/coding2017/basic/LinkedList.java @@ -2,142 +2,131 @@ public class LinkedList implements List,Iterator { - private Node head; - - private Node current; + public Node head; private int size=0; - public void add(Object o){ - Node n = new Node(); - n.next=this.head; - n.data=o; - this.head=n; + private static class Node{ + Object data; + Node next; } - public void add(int index , Object o){ - + + public Iterator iterator(){ + return null; + } + + public boolean hasNext(){ + return false; + } + + public Object next(){ + return null; + } + + public void add(Object o){ + if (head == null){ + head = new Node(); + Node n = new Node(); + n.data = o; + head.next = n; + size++; + head.data=size; + }else{ + Node e = head.next; + while (e.next!=null){ + e=e.next; + } + Node n = new Node(); + n.data = o; + e.next=n; + size++; + head.data=size; + } } + public Object get(int index){ - Node c = this.head; + int len=Integer.parseInt(head.data.toString()); + if (index>len||index<=0){ + throw new RuntimeException("下标不存在"+index); + } + Node e = head; int i=0; - while(c!=null){ + while (e.next != null){ i++; - if (index==i){ - return c.data; + if (i == index){ + return e.next.data; } - c=c.next; + e=e.next; } return null; } + public Object remove(int index){ - int s=size(); - if (s==index){ - Node n=head.next; - head=n; - return null; + int len=Integer.parseInt(head.data.toString()); + if (index>len||index<=0){ + throw new RuntimeException("下标不存在"+index); } - Node n=head; - Node p = null; - while (n!=null){ - s--; - if (s==index){ - p=n.next; - n.next=p.next; - break; + Node e = head; + Object data = null; + int i=0; + while (e.next != null){ + i++; + if (i == index){ + len--; + head.data = len; + data = e.next.data; + e.next = e.next.next; + return data; } - n=n.next; + e=e.next; } return null; } - public void listNode(){ - Node c = this.head; - while(c!=null){ - System.out.print(c.data+ " -> "); - c=c.next; - } - System.out.println(); + public Object removeFirst(){ + return remove(1); } - public int size(){ - size=0; - Node c = this.head; - while(c!=null){ - size++; - c=c.next; - } - return size; + public Object removeLast(){ + return remove(Integer.parseInt(head.data.toString())); } public void addFirst(Object o){ - if (this.head==null){ - this.head = new Node(); - this.head.data=o; - }else{ - Node f = new Node(); - Node n=head; - Node p=null; - while (n!=null){ - p=n; - n=n.next; - } - f.data=o; - p.next=f; - } + Node e = head.next; + Node n = new Node(); + n.data=o; + n.next=e; + size++; + head.next=n; + head.data=size; } + public void addLast(Object o){ add(o); } - public Object removeFirst(){ - remove(1); - return null; - } - public Object removeLast(){ - remove(size()); - return null; - } - public Iterator iterator(){ - LinkedList l = new LinkedList(); - l.head=this.head; - return l; + public int size(){ + return Integer.parseInt(head.data.toString()); } - public boolean hasNext(){ - current = head; - if (current!=null){ - head = current.next; - return true; + public void listNode(){ + Node n = head; + StringBuffer buffer = new StringBuffer(); + while (n.next!=null){ + buffer.append(n.next.data + " -> "); + n=n.next; + } + if(buffer.length()>0){ + System.out.print(buffer.substring(0,buffer.length()-3)); + System.out.println(); } - return false; - } - - public Object next(){ - return current.data; - } - - - private static class Node{ - Object data; - Node next; - } /** * 把该链表逆置 * 例如链表为 3->7->10 , 逆置后变为 10->7->3 */ - public void reverse(){ - - } - - /** - * 删除一个单链表的前半部分 - * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 - * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 - - */ - public void removeFirstHalf(){ + public void reverse(){ } @@ -146,9 +135,33 @@ public void removeFirstHalf(){ * @param i * @param length */ - public void remove(int i, int length){ - + public void remove(int i, int length){ + if (i <= 0 || length<=0){ + throw new RuntimeException("起始值、结束值都不能小于0等于"); + } + int len = length + i; + if (len > size){ + throw new RuntimeException("删除索引长度超过了链表长度"); + } + Node e = head; + int y = 0; + while (e.next != null){ + y++; + if (y == i){ + Node n = e.next; + while (n!=null){ + n = n.next; + if (y == length){ + break; + } + y++; + n=n.next; + } + } + e=e.next; + } } + /** * 假定当前链表和list均包含已升序排列的整数 * 从当前链表中取出那些list所指定的元素 @@ -157,8 +170,40 @@ public void remove(int i, int length){ * 返回的结果应该是[101,301,401,601] * @param list */ - public static int[] getElements(LinkedList list){ - return null; + public int[] getElements(LinkedList list){ + if (list==null||list.head==null){ + throw new RuntimeException("集合没有初始化"); + } + int[] elements = new int[Integer.parseInt(list.head.data.toString())]; + Node l = list.head; + Node n = head; + int len = 0; + int i = 0; + while (l.next!=null){ + len = 0; + n=head; + while(n.next!=null){ + len++; + if(len==Integer.parseInt(l.next.data.toString())){ + elements[i]=Integer.parseInt(n.next.data.toString()); + i++; + break; + } + n=n.next; + } + l = l.next; + } + return elements; + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + } /** @@ -168,26 +213,61 @@ public static int[] getElements(LinkedList list){ * @param list */ - public void subtract(LinkedList list){ - + public void subtract(LinkedList list){ + if (list==null||list.head==null){ + throw new RuntimeException("集合没有初始化"); + } + Node l = list.head; + Node n = head; + int i = 0; + while (l.next!=null){ + n=head; + i=0; + while(n.next!=null){ + i++; + if(n.next.data.equals(l.next.data)){ + remove(i); + break; + } + n=n.next; + } + l = l.next; + } } /** * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) */ - public void removeDuplicateValues(){ + public void removeDuplicateValues(){ } /** * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * 11->101->201->301->401->501->601->701 * @param min * @param max */ - public void removeRange(int min, int max){ - + public void removeRange(int min, int max){ + if (min<=0||max<=0||min>max){ + throw new RuntimeException("录入不正确:"+min+","+max+" 应该大于min且小于max的元素"); + } + Node n = head; + int data = 0; + Node p = null; + while(n.next != null){ + data=Integer.parseInt(n.next.data.toString()); //11 + if(data>min&&data 0){ + newArry[i++] = origin[--j]; + } + return newArry; + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public static int[] removeZero(int[] oldArray){ + int[] tempArray = new int[oldArray.length]; + int j = 0; + for(int i = 0; i < oldArray.length;i++){ + if(oldArray[i] > 0){ + tempArray[j++] = oldArray[i]; + } + } + int[] newArray = new int[j]; + System.arraycopy(tempArray, 0, newArray, 0, j); + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public static int[] merge(int[] array1, int[] array2){ + int len = array1.length; + int[] newArray = new int[array1.length+array2.length]; + System.arraycopy(array1, 0, newArray, 0, array1.length); + for(int i = 0; i < array2.length; i++){ + boolean flag = true; + for(int j = 0; j < array1.length; j++){ + if(array2[i] == array1[j]){ + flag = false; + } + } + if(flag){ + newArray[len++] = array2[i]; + } + } + int[] aa = new int[len]; + System.arraycopy(newArray, 0, aa, 0, len); + for(int i = 0; i < aa.length; i++){ + for(int j = i+1; j < aa.length; j++){ + if(aa[i] > aa[j]){ + int temp = aa[i]; + aa[i] = aa[j]; + aa[j] = temp; + } + } + } + return aa; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public static int[] grow(int [] oldArray, int size){ + int[] aa = new int[oldArray.length+size]; + System.arraycopy(oldArray, 0, aa, 0, oldArray.length); + return aa; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * Fn = F(n-1)+F(n-2)(n >= 2) + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public static int[] fibonacci(int max){ + if(max <2){ + return new int[0]; + } + int[] temp = new int[8]; + int count = 0; + for(int i = 1;i < max;i ++){ + int len = createFibo(i); + if(len > max) + break; + temp = growInt(temp,count); + temp[count++] = len; + } + int[] res = new int[count]; + System.arraycopy(temp, 0, res, 0, count); + return res; + } + + private static int[] growInt(int[] temp,int count){ + int[] n = temp; + if(count >= temp.length){ + n = new int[temp.length + (temp.length >> 1)]; + System.arraycopy(temp, 0, n, 0, temp.length); + } + return n; + } + + private static int createFibo(int n){ + if(n <= 2){ + return 1; + } + return createFibo(n-1)+createFibo(n-2); + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder str = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + str.append(seperator).append(array[i]); + } + return str.substring(1).toString(); + } + +} diff --git a/group10/595128841/src/main/java/org/le/b/LoginAction.java b/group10/595128841/src/main/java/org/le/b/LoginAction.java new file mode 100644 index 0000000000..d895f6b5e6 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/b/LoginAction.java @@ -0,0 +1,35 @@ +package org.le.b; + +public class LoginAction { + + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group10/595128841/src/main/java/org/le/b/Struts.java b/group10/595128841/src/main/java/org/le/b/Struts.java new file mode 100644 index 0000000000..303286690f --- /dev/null +++ b/group10/595128841/src/main/java/org/le/b/Struts.java @@ -0,0 +1,155 @@ +package org.le.b; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentFactory; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +public class Struts { + private static Map actionMap; + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + if(actionMap == null){ + actionMap = strutsXmlSax("struts2.xml"); + } + ActionBean actionBean = actionMap.get(actionName); + return processAction(actionBean,parameters); + } + + + private static View processAction(ActionBean actionBean, Map parameters) { + String clazzStr = actionBean.getClazz(); + Map result = actionBean.getResults(); + try { + Class clazz= Class.forName(clazzStr); + Object obj = clazz.newInstance(); + for(String key : parameters.keySet()){ + String name = "set"+(key.charAt(0)+"").toUpperCase()+key.substring(1); + Method method = clazz.getMethod(name, String.class); + method.invoke(obj, parameters.get(key)); + } + Method execute = clazz.getMethod("execute"); + String resultStr = (String)execute.invoke(obj); + String resultJsp = result.get(resultStr); + Map pramMap = new HashMap<>(); + Method meg = clazz.getMethod("getMessage"); + String resultMsg = (String)meg.invoke(obj); + pramMap.put("message", resultMsg); + return new View(resultJsp,pramMap); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } + return null; + } + + + public static Map strutsXmlSax(String path){ + DocumentFactory documentFactory = DocumentFactory.getInstance(); + SAXReader saxReader = new SAXReader(documentFactory); + Document doc = null; + try { + doc = saxReader.read(path); + } catch (DocumentException e) { + e.printStackTrace(); + } + Element rootElement = doc.getRootElement(); + Element pack = rootElement.element("package"); + List actions = pack.elements("action"); + Map actionMap = new HashMap<>(); + for(Element action : actions){ + Attribute name = action.attribute("name"); + Attribute clazz = action.attribute("class"); + List results = action.elements("result"); + Map resMap = new HashMap<>(); + for(Element result : results){ + String key = "success"; + String value = result.getTextTrim(); + Attribute rname = result.attribute("name"); + if(rname != null){ + key = rname.getValue(); + } + resMap.put(key, value); + } + actionMap.put(name.getValue(), new ActionBean(name.getValue(),clazz.getValue(),resMap)); + } + return actionMap; + } + + public static class ActionBean{ + private String name; + private String clazz; + private Map results; + + public ActionBean(String name, String clazz, Map results) { + this.name = name; + this.clazz = clazz; + this.results = results; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClazz() { + return clazz; + } + + public void setClazz(String clazz) { + this.clazz = clazz; + } + + public Map getResults() { + return results; + } + + public void setResults(Map results) { + this.results = results; + } + + } + +} diff --git a/group10/595128841/src/main/java/org/le/b/StrutsTest.java b/group10/595128841/src/main/java/org/le/b/StrutsTest.java new file mode 100644 index 0000000000..3733a6a777 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/b/StrutsTest.java @@ -0,0 +1,38 @@ +package org.le.b; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group10/595128841/src/main/java/org/le/b/View.java b/group10/595128841/src/main/java/org/le/b/View.java new file mode 100644 index 0000000000..39a9f8a644 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/b/View.java @@ -0,0 +1,28 @@ +package org.le.b; + +import java.util.Map; + +public class View { + + private String jsp; + private Map parameters; + + public View(String resultJsp, Map pramMap) { + this.jsp = resultJsp; + this.parameters = pramMap; + } + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group10/595128841/src/main/java/org/le/c/Downloader.java b/group10/595128841/src/main/java/org/le/c/Downloader.java new file mode 100644 index 0000000000..811bb711a4 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/c/Downloader.java @@ -0,0 +1,120 @@ +/** + * + */ +package org.le.c; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +/** + * 多线程图片下载 + * @author yue + * @time 2017年3月11日 + */ +public class Downloader { + + private RandomAccessFile raf; + private String url; + + public Downloader(String url,String path){ + //获取文件名 + String filePath = path+File.separator+url.substring(url.lastIndexOf("/")+1); + System.out.println("保存路径:"+filePath); + this.url = url; + try { + this.raf = new RandomAccessFile(filePath,"rw"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public void downFile() throws IOException{ + URL uurl = new URL(url); + URLConnection conn = uurl.openConnection(); + int cLen = conn.getContentLength();//最大可表示4G + if(cLen < 0){ + System.out.println("无法获取文件大小"); + return; + } + this.raf.setLength(cLen); + //根据文件大小选择合适线程 + int size = getByteArrayLength(cLen); + byte[] buff = new byte[size]; + System.out.println("下载文件:"+url+",文件大小:"+cLen+"字节,单个线程大小:"+size); + int len = 0; + int offset = 0; + int index = 0; + try (InputStream in = conn.getInputStream()){ + while((len = in.read(buff)) != -1){ + byte[] desc = getNewByte(buff,len); + Thread thread = new DownLoadThread(desc,offset,this); + offset += len; + thread.setName("线程"+(++index)); + thread.start(); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + + private byte[] getNewByte(byte[] src,int len){ + byte[] desc = new byte[len]; + System.arraycopy(src, 0, desc, 0, len); + return desc; + } + + private int getByteArrayLength(int cLen) { + int m = 1024 * 1024; + int s = cLen/m; + if(s == 0){ + return 1024 *100; + } + return m; + } + + public synchronized void writeToFile(byte[] buff,int offset) { + try { + raf.seek(offset); + raf.write(buff); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public static void main(String[] args) throws Exception { + String url = "http://7xq43s.com1.z0.glb.clouddn.com/yunanding-6.jpg"; + String path = "C:/work/workspace/coding2017/coding2017/group10/595128841"; + Downloader d = new Downloader(url,path); + long st = System.currentTimeMillis(); + d.downFile(); + System.out.println("耗时:"+(System.currentTimeMillis() - st)+" 毫秒"); + } + + static class DownLoadThread extends Thread{ + private byte[] buff; + private int offset; + private Downloader downloader; + + public DownLoadThread(byte[] buff, int offset,Downloader downloader) { + this.buff = buff; + this.downloader = downloader; + this.offset = offset; + } + + @Override + public void run() { + System.out.println(Thread.currentThread().getName()+",length:"+buff.length+",offset:"+offset); + downloader.writeToFile(buff,offset); + } + + } + + +} diff --git a/group10/595128841/src/main/java/org/le/c/ImgFilter.java b/group10/595128841/src/main/java/org/le/c/ImgFilter.java new file mode 100644 index 0000000000..2ce1767d32 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/c/ImgFilter.java @@ -0,0 +1,25 @@ +/** + * + */ +package org.le.c; + +import java.io.File; +import java.io.FilenameFilter; + +/** + * 图片过滤器 + * @author yue + * @time 2017年3月12日 + */ +public class ImgFilter implements FilenameFilter { + + /** + * + */ + @Override + public boolean accept(File dir, String name) { + String s1 = name.toLowerCase(); + return s1.endsWith(".jpg") || s1.endsWith(".png"); + } + +} diff --git a/group10/595128841/src/main/java/org/le/list/ArrayList.java b/group10/595128841/src/main/java/org/le/list/ArrayList.java new file mode 100644 index 0000000000..03a74e139b --- /dev/null +++ b/group10/595128841/src/main/java/org/le/list/ArrayList.java @@ -0,0 +1,144 @@ +/** + * + */ +package org.le.list; + +/** + * @author yue + * @time 2017年2月19日 + */ +public class ArrayList implements List { + + private Object[] elementData; + + private int size; + + public ArrayList(int initCapcity){ + if(initCapcity < 0){ + throw new IllegalArgumentException("initCapcity 必须大于0"); + } + elementData = new Object[initCapcity]; + } + + public ArrayList(){ + elementData = new Object[10]; + } + + @Override + public void add(Object obj) { + grow(size + 1); + elementData[size++] = obj; + } + + @Override + public void add(int index, Object obj) { + rangeCheckForAdd(index); + grow(size + 1); + System.arraycopy(elementData, index, elementData, index+1, size - index); + elementData[index] = obj; + size ++; + } + + @Override + public void remove(Object obj) { + if(obj == null){ + for (int i = 0; i < size; i++) { + if(elementData[i] == null){ + fastRemove(i); + } + } + }else{ + for (int i = 0; i < size; i++) { + if(obj.equals(elementData[i])){ + fastRemove(i); + } + } + } + } + + @Override + public E remove(int index) { + rangeCheck(index); + int movedNum = size - index - 1; + E oldElement = elementData(index); + System.arraycopy(elementData, index+1, elementData, index, movedNum); + elementData[--size] = null; + return oldElement; + } + + @Override + public E get(int index) { + rangeCheck(index); + return elementData(index); + } + + @Override + public E set(int index, E obj) { + rangeCheck(index); + E oldElement = elementData(index); + elementData[index] = obj; + return oldElement; + } + + @Override + public int indexOf(E obj) { + if(obj == null){ + for (int i = 0; i < size; i++) { + if(elementData[i] == null){ + return i; + } + } + }else{ + for (int i = 0; i < size; i++) { + if(obj.equals(elementData[i])){ + return i; + } + } + } + return -1; + } + + /** + * 数组扩容 + * @param minCapacity + */ + private void grow(int minCapacity) { + if(minCapacity <= elementData.length){ + return; + } + int oldCapacity = elementData.length; + int newCapacity = minCapacity + (oldCapacity >> 1); + if(newCapacity < minCapacity){ + newCapacity = minCapacity; + } + if(minCapacity > Integer.MAX_VALUE){ + newCapacity = Integer.MAX_VALUE; + } + Object[] newArray = new Object[newCapacity]; + System.arraycopy(elementData, 0, newArray, 0, newCapacity); + elementData = newArray; + } + + @SuppressWarnings("unchecked") + private E elementData(int index){ + return (E) elementData[index]; + } + + private void fastRemove(int i) { + int numMoved = size - i -1; + if(numMoved > 0){ + System.arraycopy(elementData, i+1, elementData, i, numMoved); + } + elementData[-- size] = null; + } + + private void rangeCheck(int index){ + if(index >= size || index <0) + throw new IndexOutOfBoundsException("index:"+index+",size:"+size); + } + + private void rangeCheckForAdd(int index){ + if(index > size || index <0) + throw new IndexOutOfBoundsException("index:"+index+",size:"+size); + } +} diff --git a/group10/595128841/src/main/java/org/le/list/LinkedList.java b/group10/595128841/src/main/java/org/le/list/LinkedList.java new file mode 100644 index 0000000000..b4ee384ad6 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/list/LinkedList.java @@ -0,0 +1,299 @@ +/** + * + */ +package org.le.list; + +import java.util.NoSuchElementException; + +/** + * @author yue + * @time 2017年2月19日 + */ +public class LinkedList implements List { + + private int size = 0; + + private Node first; + + private Node last; + + private static class Node{ + E item; + Node prev; + Node next; + Node(Node prev,E item, Node next) { + super(); + this.item = item; + this.prev = prev; + this.next = next; + } + } + + public LinkedList(){ + + } + + /** + * 头部插入 + */ + private void linkFirst(E e){ + final Node f = first; + final Node newNode = new Node(null,e,f); + first = newNode; + if(f == null) + last = newNode; + else + f.prev = newNode; + size ++; + } + + /** + * 尾部插入 + */ + private void linkLast(E e){ + final Node l = last; + final Node newNode = new Node<>(l,e,null); + last = newNode; + if(last == null) + first = newNode; + else + l.next = newNode; + size ++; + } + + /** + * 某个不为null元素之前插入 + */ + private void linkBefore(E e,Node succ){ + final Node pred = succ.prev; + final Node newNode = new Node<>(pred,e,succ); + succ.prev = newNode; + if(pred == null) + first = newNode; + else + pred.next = newNode; + size ++; + } + + /** + * 删除头部元素 + */ + private E unlinkFirst(Node f){ + final E element = f.item; + final Node next = f.next; + f.item = null; + f.next = null; + first = next; + if(next == null) + last = null; + else + next.prev = null; + size -- ; + return element; + } + /** + * 删除尾部元素 + * @param l + * @return + */ + private E unlinkLast(Node l){ + final E element = l.item; + final Node prev = l.prev; + l.item = null; + l.prev = null; + last = prev; + if(prev == null) + first = null; + else + prev.next = null; + size -- ; + return element; + } + + /** + * 删除指定节点 + * @param e + * @return + */ + private E unlink(Node e){ + final Node prev = e.prev; + final E element = e.item; + final Node next = e.next; + + if(prev == null){ + first = next; + }else{ + prev.next = next; + e.prev = null; + } + + if(next == null){ + last = prev; + }else{ + next.prev = prev; + e.next = null; + } + e.item = null; + size -- ; + return element; + } + + /** + * 该方法默认在尾部添加 + */ + @Override + public void add(E e) { + linkLast(e); + } + + /** + * + */ + @Override + public void add(int index, E e) { + checkPositionIndex(index); + if(index == size){ + linkLast(e); + }else{ + linkBefore(e, node(index)); + } + } + + private Node node(int index) { + //小于容量一半 + if(index < (size >> 1)){ + Node x = first; + for(int i = 0; i < index; i++){ + x = x.next; + } + return x; + }else{ + Node x = last; + for(int i = size - 1; i > index; i --){ + x = x.prev; + } + return x; + } + } + + private void checkPositionIndex(int index){ + if(index <0 || index > size){ + throw new IndexOutOfBoundsException("索引越界:index:"+index+",size:"+size); + } + } + + private void checkElementIndex(int index){ + if(index <0 || index >= size){ + throw new IndexOutOfBoundsException("索引越界:index:"+index+",size:"+size); + } + } + + /** + * + */ + @Override + public void remove(E obj) { + if(obj == null){ + for(Node x = first;x != null; x = x.next){ + if(x.item == null){ + unlink(x); + } + } + }else{ + for(Node x = first;x != null;x = x.next){ + if(obj.equals(x.item)){ + unlink(x); + } + } + } + } + + /** + * + */ + @Override + public E remove(int index) { + checkElementIndex(index); + return unlink(node(index)); + } + + /** + * + */ + @Override + public E get(int index) { + checkElementIndex(index); + return node(index).item; + } + + /** + * + */ + @Override + public E set(int index, E obj) { + checkElementIndex(index); + Node x = node(index); + E oldVal = x.item; + x.item = obj; + return oldVal; + } + + /** + * + */ + @Override + public int indexOf(E obj) { + int index = 0; + if(obj == null){ + for(Node x = first;x != null;x = x.next){ + if(x.item == null) + return index; + index ++; + } + }else{ + for(Node x = first; x != null; x = x.next){ + if(obj.equals(x.item)) + return index; + index ++; + } + } + return -1; + } + /** + * 弹出栈顶的元素,不删除元素 + * @param e + * @return + */ + public E peek(){ + final Node e = first; + return e == null ? null : e.item; + } + + /** + * 弹出栈顶元素,删除元素 + * @return + */ + public E poll(){ + final Node e = first; + return (e == null) ? null : unlinkFirst(e); + } + /** + * 入栈,栈顶 + * @param e + */ + public void push(E e){ + linkFirst(e); + } + + /** + * 出栈,删除并返回栈顶元素 + * @return + */ + public E pop(){ + final Node f = first; + if(f == null) + throw new NoSuchElementException(); + return unlinkFirst(f); + } + +} diff --git a/group10/595128841/src/main/java/org/le/list/List.java b/group10/595128841/src/main/java/org/le/list/List.java new file mode 100644 index 0000000000..3e50bd5553 --- /dev/null +++ b/group10/595128841/src/main/java/org/le/list/List.java @@ -0,0 +1,19 @@ +package org.le.list; + +public interface List { + + void add(E obj); + + void add(int index,E obj); + + void remove(E obj); + + E remove(int index); + + E get(int index); + + E set(int index,E obj); + + int indexOf(E obj); + +} diff --git a/group10/904627477/.settings/org.eclipse.core.resources.prefs b/group10/904627477/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000..4824b80263 --- /dev/null +++ b/group10/904627477/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/group10/904627477/src/com/coding/LinkedList.java b/group10/904627477/src/com/coding/LinkedList.java deleted file mode 100644 index f878f75820..0000000000 --- a/group10/904627477/src/com/coding/LinkedList.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.coding; - -import java.util.NoSuchElementException; - -public class LinkedList implements List { - - private Node head; - - public void add(Object o){ - addLast(o); - } - - public void add(int index , Object o){ - Node node = new Node(); - node.data = o; - if(index==0){ - addFirst(o); - return ; - } - Node before = getNode(index-1); - Node next = before.next; - before.next = node; - node.next = next; - } - - private Node getLastNode(){ - Node temp = head; - if(head!=null){ - while(true){ - if(temp.next!=null){ - temp = temp.next; - }else{ - break; - } - } - }else{ - throw new NoSuchElementException(); - } - return temp; - } - - private Node getNode(int index){ - if(index<0){ - throw new IndexOutOfBoundsException(); - } - int i = 0; - Node temp = head; - while(true){ - if(temp==null){ - throw new IndexOutOfBoundsException(); - } - if(i==index){ - break; - }else{ - i++; - temp = temp.next; - } - } - return temp; - } - - public Object get(int index){ - Node node = getNode(index); - return node.data; - } - - public Object remove(int index){ - if(index==0){ - removeFirst(); - } - Node before = getNode(index-1); - Node temp = getNode(index); - before.next = temp.next; - return temp.data; - } - - public int size(){ - int size = 0; - Node temp = head; - while(true){ - if(temp==null){ - break; - }else{ - size++; - temp = temp.next; - } - } - return size; - } - - public void addFirst(Object o){ - Node node = new Node(); - node.data = o; - node.next = head; - head = node; - } - - public void addLast(Object o){ - Node node = new Node(); - node.data = o; - if(head==null){ - head = node; - return; - } - Node last = getLastNode(); - last.next = node; - } - public Object removeFirst(){ - if(head == null){ - throw new NoSuchElementException(); - } - Object obj = head.data; - head = head.next; - return obj; - } - public Object removeLast(){ - if(head == null){ - throw new NoSuchElementException(); - } - if(head.next == null){ - return removeFirst(); - } - Node before = head; - Node temp = head.next; - while(true){ - if(temp.next==null){ - break; - }else{ - before = temp; - temp = temp.next; - } - } - before.next = null; - return temp.data; - } - - public Iterator iterator(){ - return new LinkedIterator(); - } - - - private static class Node{ - Object data; - Node next; - } - - private class LinkedIterator implements Iterator{ - - private Node node; - - public LinkedIterator(){ - node = head; - } - - @Override - public boolean hasNext() { - if(node!=null){ - return true; - } - return false; - } - - @Override - public Object next() { - if(node==null){ - throw new NoSuchElementException(); - }else{ - Object obj = node.data; - node = node.next; - return obj; - } - } - - } -} diff --git a/group10/904627477/src/com/coding/array/ArrayUtil.java b/group10/904627477/src/com/coding/array/ArrayUtil.java index 37f230812a..aaa1dbb96a 100644 --- a/group10/904627477/src/com/coding/array/ArrayUtil.java +++ b/group10/904627477/src/com/coding/array/ArrayUtil.java @@ -10,6 +10,9 @@ public class ArrayUtil { * @return */ public void reverseArray(int[] origin){ + if(origin==null){ + return ; + } int len = origin.length; for (int i = 0; i < len/2 ; i++) { int temp = origin[len-1-i]; @@ -27,6 +30,9 @@ public void reverseArray(int[] origin){ */ public int[] removeZero(int[] oldArray){ + if(oldArray==null){ + return new int[0]; + } int[] tempArr = new int[oldArray.length]; int size = 0; for (int i = 0; i < oldArray.length; i++) { @@ -49,6 +55,11 @@ public int[] removeZero(int[] oldArray){ */ public int[] merge(int[] array1, int[] array2){ + if(array1==null&&array2==null){ + return new int[0]; + }else if(array1==null||array2==null){ + return array1==null?array2:array1; + } int[] arr3 = new int[array1.length+array2.length]; int len1 = array1.length; int len2 = array2.length; @@ -85,6 +96,9 @@ public int[] merge(int[] array1, int[] array2){ * @return */ public int[] grow(int [] oldArray, int size){ + if(oldArray==null){ + return new int[0]; + } if(size<0){ throw new IllegalArgumentException(); } @@ -95,6 +109,20 @@ public int[] grow(int [] oldArray, int size){ return newArr; } + public static byte[] grow(byte[] oldArray, int size){ + if(oldArray==null){ + return new byte[0]; + } + if(size<0){ + throw new IllegalArgumentException(); + } + byte[] newArr = new byte[oldArray.length + size]; + for (int i = 0; i < oldArray.length; i++) { + newArr[i] = oldArray[i]; + } + return newArr; + } + /** * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] @@ -202,13 +230,28 @@ public boolean isPerfectNumber(int n){ * @param s * @return */ - public String join(int[] array, String seperator){ + /*My + public String join(int[] array, String seperator){ String result = ""; for (int i = 0; i < array.length; i++) { result = result + array[i] + seperator; } int index = result.lastIndexOf(seperator); return result.substring(0, index); + }*/ + + public String join(int[] array, String seperator){ + if(array==null){ + return ""; + } + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < array.length; i++) { + sb.append(array[i]); + if(i7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + if (head == null || head.next == null) { + return; + } + Node temp = head.next; + Node newHead = this.head; + newHead.next = null; + while (temp != null) { + Node next = temp.next; + temp.next = newHead; + newHead = temp; + temp = next; + } + this.head = newHead; + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + */ + public void removeFirstHalf() { + if (head == null || head.next == null) { + return; + } + int len = size(); + for (int i = 0; i < len / 2; i++) { + head = head.next; + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + if (i < 0 || i >= size()) { + throw new IndexOutOfBoundsException(); + } + if(head==null){ + return; + } + Node ni = head; + Node temp = head; + for (int j = 0; j < i + length; j++) { + if (temp == null) { + break; + } + if (j + 1 == i) { + ni = temp; + } + temp = temp.next; + } + ni.next = temp; + if (i == 0) { + head = temp; + } + } + + /** + * 假定当前链表和listB均包含已升序排列的整数 从当前链表中取出那些listB所指定的元素 例如当前链表 = + * 11->101->201->301->401->501->601->701 listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * + * @param list + */ + public int[] getElements(LinkedList list) { + if(list==null||head==null||list.head==null){ + return new int[0]; + } + int[] arr = new int[0]; + Node tempA = head; + Node tempB = list.head; + int index=0; + while(tempA!=null&&tempB!=null){ + int len = (int)tempB.data - index; + int i = 0; + for(i=0;i=max){ + return ; + } + Node temp = new Node(); + temp.next = head; + while(temp.next!=null){ + if(temp.next.data==null){ + temp = temp.next; + continue; + } + int d = (int) temp.next.data; + if(d>min&&d=max){ + break; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) { + LinkedList link = new LinkedList(); + if(list==null||head==null||list.head==null){ + return link; + } + Node tempA = new Node(); + tempA.next = head; + Node tempB = new Node(); + tempB.next = list.head; + while(tempA.next!=null&&tempB.next!=null){ + if(tempA.next.data==null){ + tempA = tempA.next; + continue; + } + if(tempB.next.data==null){ + tempB = tempB.next; + continue; + } + int a = (int)tempA.next.data; + int b = (int)tempB.next.data; + if(ab){ + tempB = tempB.next; + }else{ + link.add(tempA.next.data); + tempA = tempA.next; + tempB = tempB.next; + } + } + return link; + } +} diff --git a/group13/1274639949/lesson01/src/com/hans/List.java b/group10/904627477/src/com/coding/basic/List.java similarity index 79% rename from group13/1274639949/lesson01/src/com/hans/List.java rename to group10/904627477/src/com/coding/basic/List.java index f8ffaa8f5e..396b1f6416 100644 --- a/group13/1274639949/lesson01/src/com/hans/List.java +++ b/group10/904627477/src/com/coding/basic/List.java @@ -1,10 +1,9 @@ -package com.hans; - -public interface List { - public void add(Object o); - public void add(int index, Object o); - public Object get(int index); - public Object remove(int index); - public int size(); - public Iterator iterator(); -} +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group10/904627477/src/com/coding/Queue.java b/group10/904627477/src/com/coding/basic/Queue.java similarity index 88% rename from group10/904627477/src/com/coding/Queue.java rename to group10/904627477/src/com/coding/basic/Queue.java index 8fd01bef96..2b2f92f74b 100644 --- a/group10/904627477/src/com/coding/Queue.java +++ b/group10/904627477/src/com/coding/basic/Queue.java @@ -1,4 +1,4 @@ -package com.coding; +package com.coding.basic; public class Queue { diff --git a/group10/904627477/src/com/coding/Stack.java b/group10/904627477/src/com/coding/basic/Stack.java similarity index 90% rename from group10/904627477/src/com/coding/Stack.java rename to group10/904627477/src/com/coding/basic/Stack.java index 3f8b319607..083215e615 100644 --- a/group10/904627477/src/com/coding/Stack.java +++ b/group10/904627477/src/com/coding/basic/Stack.java @@ -1,4 +1,4 @@ -package com.coding; +package com.coding.basic; import java.util.EmptyStackException; diff --git a/group10/904627477/src/com/coding/download/CreateThread.java b/group10/904627477/src/com/coding/download/CreateThread.java new file mode 100644 index 0000000000..d9a22edbbd --- /dev/null +++ b/group10/904627477/src/com/coding/download/CreateThread.java @@ -0,0 +1,32 @@ +package com.coding.download; + + +import com.coding.download.api.Resource; + +public class CreateThread extends Thread { + + private Resource resource; + private int length; + + public CreateThread(Resource resource,int length){ + this.resource = resource; + this.length = length; + } + + @Override + public void run() { + int startPos = 0; + while(true){ + //System.out.println(startPos); + if(startPos>=length){ + resource.setFlag(true); + break; + }else{ + startPos = resource.increace(); + } + } + } + + + +} diff --git a/group10/904627477/src/com/coding/download/DownloadThread.java b/group10/904627477/src/com/coding/download/DownloadThread.java new file mode 100644 index 0000000000..7e98539050 --- /dev/null +++ b/group10/904627477/src/com/coding/download/DownloadThread.java @@ -0,0 +1,36 @@ +package com.coding.download; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +import com.coding.download.api.Connection; +import com.coding.util.IOUtils; + +public class DownloadThread extends Thread { + + Connection conn; + int startPos; + int endPos; + private File file; + + public DownloadThread(Connection conn, int startPos, int endPos,File file) { + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.file = file; + } + + public void run() { + byte[] buff; + try { + buff = conn.read(startPos, endPos); + if(buff!=null&&buff.length!=0){ + IOUtils.writeFile(file, startPos, buff); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/group10/904627477/src/com/coding/download/FileDownloader.java b/group10/904627477/src/com/coding/download/FileDownloader.java new file mode 100644 index 0000000000..146491f2db --- /dev/null +++ b/group10/904627477/src/com/coding/download/FileDownloader.java @@ -0,0 +1,102 @@ +package com.coding.download; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; + +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; +import com.coding.download.api.ConnectionManager; +import com.coding.download.api.DownloadListener; +import com.coding.download.api.Resource; +import com.coding.util.IOUtils; + + + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + private static String localFile = "c:/test/test.jpg"; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + /**/ + try { + Connection conn = cm.open(url); + int length = conn.getContentLength(); + File file = new File(localFile); + if(!file.exists()){ + IOUtils.createFile(length, localFile); + } + Resource res = new Resource(url,file); + Thread c = new CreateThread(res,length); + Thread r = new RemoveThread(res,listener); + c.start(); + r.start(); + } catch (ConnectionException e) { + e.printStackTrace(); + } + /*Connection conn = null; + try { + conn = cm.open(this.url); + int length = conn.getContentLength(); + File file = new File(localFile); + if(!file.exists()){ + IOUtils.createFile(length, localFile); + } + + + + new DownloadThread(cm.open(this.url),0,length-1,file).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + }*/ + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group10/904627477/src/com/coding/download/FileDownloaderTest.java b/group10/904627477/src/com/coding/download/FileDownloaderTest.java new file mode 100644 index 0000000000..f3345d75d7 --- /dev/null +++ b/group10/904627477/src/com/coding/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coding.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coding.download.api.ConnectionManager; +import com.coding.download.api.DownloadListener; +import com.coding.download.impl.ConnectionManagerImpl; + + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "https://img6.bdstatic.com/img/image/smallpic/22.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/group10/904627477/src/com/coding/download/RemoveThread.java b/group10/904627477/src/com/coding/download/RemoveThread.java new file mode 100644 index 0000000000..0a1b5e415f --- /dev/null +++ b/group10/904627477/src/com/coding/download/RemoveThread.java @@ -0,0 +1,30 @@ +package com.coding.download; + +import com.coding.download.api.DownloadListener; +import com.coding.download.api.Resource; + +public class RemoveThread extends Thread { + + private Resource resource; + private DownloadListener listener; + + public RemoveThread(Resource resource,DownloadListener listener){ + this.resource = resource; + this.listener = listener; + } + + @Override + public void run() { + while(true){ + if(resource.isFlag()&&resource.getThreads().size()==0){ + listener.notifyFinished(); + break; + }else{ + resource.decreace(); + } + } + } + + + +} diff --git a/group10/904627477/src/com/coding/download/api/Connection.java b/group10/904627477/src/com/coding/download/api/Connection.java new file mode 100644 index 0000000000..65f3dae9c5 --- /dev/null +++ b/group10/904627477/src/com/coding/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coding.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group10/904627477/src/com/coding/download/api/ConnectionException.java b/group10/904627477/src/com/coding/download/api/ConnectionException.java new file mode 100644 index 0000000000..67f59470a3 --- /dev/null +++ b/group10/904627477/src/com/coding/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coding.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group10/904627477/src/com/coding/download/api/ConnectionManager.java b/group10/904627477/src/com/coding/download/api/ConnectionManager.java new file mode 100644 index 0000000000..df00b84b77 --- /dev/null +++ b/group10/904627477/src/com/coding/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coding.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group10/904627477/src/com/coding/download/api/DownloadListener.java b/group10/904627477/src/com/coding/download/api/DownloadListener.java new file mode 100644 index 0000000000..bc01938d90 --- /dev/null +++ b/group10/904627477/src/com/coding/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coding.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group10/904627477/src/com/coding/download/api/Resource.java b/group10/904627477/src/com/coding/download/api/Resource.java new file mode 100644 index 0000000000..ae525fd9b5 --- /dev/null +++ b/group10/904627477/src/com/coding/download/api/Resource.java @@ -0,0 +1,92 @@ +package com.coding.download.api; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import com.coding.download.DownloadThread; +import com.coding.download.impl.ConnectionManagerImpl; + +public class Resource { + + private int index; + private int size; + private String url; + private List threads; + private File file; + private boolean flag; + + public Resource(String url,File file){ + index = 0; + size = 1024*2; + threads = new ArrayList(); + flag = false; + this.url = url; + this.file = file; + } + + public synchronized int increace(){ + //System.out.println(threads.size()); + while(threads.size()>=5){ + try { + this.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + int startPos = index*size; + try { + Connection conn = new ConnectionManagerImpl().open(url); + DownloadThread down = new DownloadThread(conn, startPos, startPos+size-1,file); + down.start(); + index ++; + threads.add(down); + this.notify(); + } catch (ConnectionException e) { + e.printStackTrace(); + } + return index*size; + } + + public synchronized void decreace(){ + //System.out.println("decreace:"+threads.size()); + while(threads.size()==0){ + try { + this.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + /*try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + }*/ + for (int i = 0; i < threads.size();i++) { + if(!threads.get(i).isAlive()){ + threads.remove(i); + this.notify(); + break; + } + } + } + + public List getThreads() { + return threads; + } + + public void setThreads(List threads) { + this.threads = threads; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + + +} diff --git a/group10/904627477/src/com/coding/download/impl/ConnectionImpl.java b/group10/904627477/src/com/coding/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..6f9ef0d6ae --- /dev/null +++ b/group10/904627477/src/com/coding/download/impl/ConnectionImpl.java @@ -0,0 +1,47 @@ +package com.coding.download.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import com.coding.array.ArrayUtil; +import com.coding.download.api.Connection; + + +public class ConnectionImpl implements Connection{ + + private URLConnection ucon; + + public ConnectionImpl(String url) throws IOException{ + URL u = new URL(url); + ucon = u.openConnection(); + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + ucon.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + InputStream in = ucon.getInputStream(); + byte[] result = new byte[0]; + byte[] buff = new byte[1024]; + int len = 0; + while((len=in.read(buff))!=-1){ + int rLen = result.length; + result =ArrayUtil.grow(result, len); + System.arraycopy(buff, 0, result, rLen, len); + } + return result; + } + + @Override + public int getContentLength() { + return ucon.getContentLength(); + } + + @Override + public void close() { + //ucon = null; + } + +} diff --git a/group10/904627477/src/com/coding/download/impl/ConnectionManagerImpl.java b/group10/904627477/src/com/coding/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..f949ddce6f --- /dev/null +++ b/group10/904627477/src/com/coding/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,22 @@ +package com.coding.download.impl; + + +import java.io.IOException; + +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; +import com.coding.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException{ + try { + return new ConnectionImpl(url); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/group10/904627477/src/com/coding/test/ArrayListTest.java b/group10/904627477/src/com/coding/test/ArrayListTest.java index d65a692351..fc711a315a 100644 --- a/group10/904627477/src/com/coding/test/ArrayListTest.java +++ b/group10/904627477/src/com/coding/test/ArrayListTest.java @@ -6,8 +6,8 @@ import org.junit.Before; import org.junit.Test; -import com.coding.ArrayList; -import com.coding.Iterator; +import com.coding.basic.ArrayList; +import com.coding.basic.Iterator; public class ArrayListTest { diff --git a/group10/904627477/src/com/coding/test/LinkedListTest.java b/group10/904627477/src/com/coding/test/LinkedListTest.java index af48a6fb0b..81d8632cfe 100644 --- a/group10/904627477/src/com/coding/test/LinkedListTest.java +++ b/group10/904627477/src/com/coding/test/LinkedListTest.java @@ -6,8 +6,8 @@ import org.junit.Before; import org.junit.Test; -import com.coding.Iterator; -import com.coding.LinkedList; +import com.coding.basic.Iterator; +import com.coding.basic.LinkedList; public class LinkedListTest { @@ -114,5 +114,152 @@ public void testIterator() { assertEquals("333", it.next()); assertEquals(false, it.hasNext()); } + + @Test + public void testReverse(){ + link.reverse(); + assertEquals(3, link.size()); + assertEquals("333", link.get(0)); + assertEquals("222", link.get(1)); + assertEquals("111", link.get(2)); + } + + @Test + public void testRemoveFirstHalf(){ + link.add("444"); + link.add("555"); + link.removeFirstHalf(); + assertEquals(3, link.size()); + assertEquals("333", link.get(0)); + link.add("666"); + link.removeFirstHalf(); + assertEquals(2, link.size()); + assertEquals("555", link.get(0)); + } + + @Test + public void testRemoveForIndex(){ + link.add("444"); + link.add("555"); + link.remove(1, 2); + assertEquals(3, link.size()); + assertEquals("444", link.get(1)); + + link.remove(2, 5); + assertEquals(2, link.size()); + + link.remove(0,1); + assertEquals(1, link.size()); + assertEquals("444", link.get(0)); + } + + @Test + //11->101->201->301->401->501->601->701 listB = 1->3->4->6 [101,301,401,601] + public void testGetElements(){ + link = new LinkedList(); + link.add(11); + link.add(101); + link.add(201); + link.add(301); + link.add(401); + link.add(501); + link.add(601); + link.add(701); + LinkedList linkB = new LinkedList(); + linkB.add(1); + linkB.add(3); + linkB.add(4); + linkB.add(6); + int[] eles = link.getElements(linkB); + assertEquals(4, eles.length); + assertEquals(101, eles[0]); + assertEquals(301, eles[1]); + assertEquals(401, eles[2]); + assertEquals(601, eles[3]); + } + + @Test + public void testSubtract(){ + link = new LinkedList(); + link.add(11); + link.add(101); + link.add(201); + link.add(301); + link.add(401); + link.add(501); + link.add(601); + link.add(701); + LinkedList linkB = new LinkedList(); + linkB.add(401); + linkB.add(201); + linkB.add(601); + link.subtract(linkB); + assertEquals(5, link.size()); + assertEquals(11, link.get(0)); + assertEquals(101, link.get(1)); + assertEquals(301, link.get(2)); + assertEquals(501, link.get(3)); + assertEquals(701, link.get(4)); + } + @Test + public void testRemoveDuplicateValues(){ + link = new LinkedList(); + link.add(11); + link.add(101); + link.add(101); + link.add(301); + link.add(401); + link.add(401); + link.removeDuplicateValues(); + assertEquals(4, link.size()); + assertEquals(11, link.get(0)); + assertEquals(101, link.get(1)); + assertEquals(301, link.get(2)); + assertEquals(401, link.get(3)); + } + + @Test + public void testRemoveRange(){ + link = new LinkedList(); + link.add(11); + link.add(101); + link.add(201); + link.add(301); + link.add(401); + link.add(501); + link.add(601); + link.add(701); + link.removeRange(200, 600); + assertEquals(4, link.size()); + assertEquals(11, link.get(0)); + assertEquals(101, link.get(1)); + assertEquals(601, link.get(2)); + assertEquals(701, link.get(3)); + } + + @Test + public void testIntersection(){ + link = new LinkedList(); + link.add(11); + link.add(101); + link.add(201); + link.add(301); + link.add(401); + link.add(501); + link.add(601); + link.add(701); + LinkedList linkB = new LinkedList(); + linkB.add(201); + linkB.add(305); + linkB.add(401); + linkB.add(504); + linkB.add(601); + LinkedList linkC = link.intersection(linkB); + assertEquals(3, linkC.size()); + assertEquals(201, linkC.get(0)); + assertEquals(401, linkC.get(1)); + assertEquals(601, linkC.get(2)); + } + } diff --git a/group10/904627477/src/com/coding/test/QueueTest.java b/group10/904627477/src/com/coding/test/QueueTest.java index 779120c0fb..5434522f14 100644 --- a/group10/904627477/src/com/coding/test/QueueTest.java +++ b/group10/904627477/src/com/coding/test/QueueTest.java @@ -6,7 +6,8 @@ import org.junit.Before; import org.junit.Test; -import com.coding.Queue; +import com.coding.basic.Queue; + public class QueueTest { diff --git a/group10/904627477/src/com/coding/test/StackTest.java b/group10/904627477/src/com/coding/test/StackTest.java index 38de36c9d9..ec96c6adcb 100644 --- a/group10/904627477/src/com/coding/test/StackTest.java +++ b/group10/904627477/src/com/coding/test/StackTest.java @@ -6,7 +6,8 @@ import org.junit.Before; import org.junit.Test; -import com.coding.Stack; +import com.coding.basic.Stack; + public class StackTest { diff --git a/group10/904627477/src/com/coding/test/Test.java b/group10/904627477/src/com/coding/test/Test.java index c8024a8c97..806eb3a1c5 100644 --- a/group10/904627477/src/com/coding/test/Test.java +++ b/group10/904627477/src/com/coding/test/Test.java @@ -1,29 +1,57 @@ package com.coding.test; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.net.URL; +import java.net.URLConnection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.coding.basic.LinkedList; +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; +import com.coding.download.impl.ConnectionManagerImpl; + public class Test { - public static void main(String[] args) { - /*int[] origin = {7, 9 , 30, 3}; - ArrayUtil au = new ArrayUtil(); - au.reverseArray(origin); - for (int i : origin) { - System.out.println(i); + public static void main(String[] args) throws IOException, ConnectionException { + /*URLConnection con = new URL("https://img6.bdstatic.com/img/image/smallpic/22.jpg").openConnection(); + InputStream in = con.getInputStream(); + System.out.println("---------------"); + + con.setRequestProperty("Range", "bytes=" + 1 + "-" + 2);*/ + /*URLConnection con = new URL("https://img6.bdstatic.com/img/image/smallpic/22.jpg").openConnection(); + con.getContentLength(); + con.connect(); + //con.setRequestProperty("Range", "bytes=" + 0 + "-" + 27573); + con.addRequestProperty("Range", "bytes=" + 0 + "-" + 27573); + System.out.println(con.getContentLength()); + InputStream in = con.getInputStream(); + int length = con.getContentLength(); + File file = new File("c:/test/test.jpg"); + //RandomAccessFile out = new RandomAccessFile(file, "rw"); + FileOutputStream out = new FileOutputStream(file); + byte[] buff = new byte[length]; + int len = 0; + while((len=in.read(buff))!=-1){ + out.write(buff, 0, len); } - */ -/* int a = 5; - System.out.println(5/2); - int[] a1 = new int[0]; - System.out.println(a1.length); - System.out.println(Math.sqrt(2));*/ -// int[] a2 = new ArrayUtil().getPerfectNumbers(100); -// for (int i = 0; i < a2.length; i++) { -// System.out.println(a2[i]); -// } - System.out.println(Test.class.getResource("").getPath()); + out.close();*/ + /**/Connection con = new ConnectionManagerImpl().open("https://img6.bdstatic.com/img/image/smallpic/22.jpg"); + byte[] buff = con.read(0, 27573); + File file = new File("c:/test/test.jpg"); + FileOutputStream out = new FileOutputStream(file); + out.write(buff); + out.close(); } } diff --git a/group10/904627477/src/com/coding/util/IOUtils.java b/group10/904627477/src/com/coding/util/IOUtils.java new file mode 100644 index 0000000000..d016d55603 --- /dev/null +++ b/group10/904627477/src/com/coding/util/IOUtils.java @@ -0,0 +1,40 @@ +package com.coding.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; + +public class IOUtils { + + public static void writeFile(File file,int startPos,byte[] buff) throws IOException{ + if(buff==null){ + return; + } + RandomAccessFile out = new RandomAccessFile(file, "rw"); + out.seek(startPos); + out.write(buff); + out.close(); + } + + public static void createFile(long length,String filePath){ + RandomAccessFile file = null; + try { + file = new RandomAccessFile(filePath, "rw"); + file.setLength(length); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally{ + if(file!=null){ + try { + file.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + +} diff --git a/group12/495473393/Coding/.gitignore b/group12/.gitignore similarity index 100% rename from group12/495473393/Coding/.gitignore rename to group12/.gitignore diff --git a/group12/2258659044/zj-2017/src/com/coderising/array/ArrayUtil.java b/group12/2258659044/zj-2017/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..3f41a350e8 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,248 @@ +package com.coderising.array; + +import com.coding.basic.ArrayList; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + int length = origin.length; + int[] temp = new int[length]; + for (int i = 0; i < length; i++) { + temp[i] = origin[length-1-i]; + } + System.arraycopy(temp, 0, origin, 0, length); + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + + int length = oldArray.length; + int[] tempArr = new int[length]; + int j = 0; + int zeroNum = 0;//储存0的个数 + for (int i = 0; i < length; i++) { + if(oldArray[i]!=0){ + tempArr[j] = oldArray[i]; + j ++; + }else{ + zeroNum ++; + } + } + //删除数组尾端的0 + int[] newArray = new int[length-zeroNum]; + System.arraycopy(tempArr, 0, newArray, 0, length-zeroNum); + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + + int length1 = array1.length; + int length2 = array2.length; + int[] array3 = new int[length1 + length2]; + //将array1、array2的值加入array3中 + System.arraycopy(array1, 0, array3, 0, length1); + System.arraycopy(array2, 0, array3, length1, length2); + int length = array3.length; + int temp; + //将array3冒泡排序 + for (int i = 0; i < length; i++) { + for (int j = 0; j < length - i; j++) { + if(array3[i]>array3[j+i]){ + temp = array3[i]; + array3[i] = array3[j+i]; + array3[j+i] = temp; + } + } + } + return duplicate(array3); + } + + /** + *去重 + */ + private int[] duplicate(int[] array){ + + for (int i = 1; i < array.length; i++) { + if(array[i-1]==array[i]){ + array[i] = 0; + } + } + return removeZero(array); + } + + /** + * 位图法合并 + * @param array1 + * @param array2 + * @return + */ + public int[] merge2(int[] array1, int[] array2){ + + int bitSize = 0; + int a = array1[array1.length-1] ; + int b = array2[array2.length-1]; + bitSize =(a>b)?a:b; + boolean[] bitmap = new boolean[bitSize+1]; + for (int i = 0; i < array1.length; i++) { + bitmap[array1[i]]=true; + } + for (int i = 0; i < array2.length; i++) { + bitmap[array2[i]]=true; + } + + ArrayList ls = new ArrayList(); + for (int i = 0; i < bitmap.length; i++) { + if(bitmap[i]==true){ + ls.add(i); + } + } + return objList2int(ls); + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + + int[] newArray = new int[oldArray.length+size]; + System.arraycopy(oldArray, 0,newArray , 0, oldArray.length); + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + + int[] array = {}; + if(max <= 1)return array; + //生成 斐波那契数列的ArrayList集合 + ArrayList ls = new ArrayList(); + ls.add(1);ls.add(1); + int next;int i = 1; + while(true){ + next = (int)ls.get(i) +(int)ls.get(i-1); + if(next >= max){ + break; + } + ls.add(next); + i ++; + } + return objList2int(ls); + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + + ArrayList primesList = new ArrayList(); + boolean flag; + for (int i = 2; i < max; i++) { + flag = false; + for (int j = 2; j <= Math.sqrt(i); j++) { + if (i % j == 0) { + flag =true; + break; + } + } + if(!flag){ + primesList.add(i); + } + } + return objList2int(primesList); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + + int temp; + ArrayList perfectList = new ArrayList(); + for (int i = 6; i <= max; i++) { + temp = 0; + for (int j = 1; j <= (i/2); j++) { + if(i%j == 0){ + temp += j; + } + } + if(temp == i){ + perfectList.add(i); + } + } + return objList2int(perfectList); + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + + StringBuilder str = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + str.append(array[i]+seperator); + } + return str.substring(0, str.lastIndexOf(seperator)); + } + + /** + * 将存储int数据的ArrayList转换为int数组 + * @param ls + * @return + */ + public int[] objList2int(ArrayList ls){ + + Object[] objArr = ls.toArray(); + int[] array = new int[ls.size()]; + for (int i = 0; i < ls.size(); i++) { + array[i] = (int) objArr[i]; + } + return array; + } + +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/DownloadThread.java b/group12/2258659044/zj-2017/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..b4d218399f --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,115 @@ +package com.coderising.download; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread { + + Connection conn; + int startPos; + int endPos; + /* 文件路径 */ + String downloadPath; + /*临时文件*/ + File tempFile; + /*文件后缀名称*/ + String sufferName; + /*当前线程下载量*/ + volatile int downloadSize; + + public DownloadThread(String downloadPath, Connection conn, int startPos, + int endPos) { + + this.downloadPath = downloadPath; + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + + /** + * 这种操作存在弊端, + * 若文件过大,调用conn.read读取过程中程序中断 + * 将无法缓存任何数据 + */ + /*public void run() { + + try { + + //请求服务器下载部分文件 指定文件的位置 读取指定位子的字节 + byte[] buffer = conn.read(startPos, endPos); + //随机访问文件流 + RandomAccessFile raf = new RandomAccessFile(tempFile, "rwd"); + //随机写文件的时候从哪个位置开始写 + raf.seek(startPos);//定位文件 + //写文件 + raf.write(buffer); + raf.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + }*/ + + public void run() { + + try { + + //修改后缀名称,并保存正确后缀名 + String name = reSufferNameAndStore(conn.getDownloadName()); + //创建临时文件 + File file = new File(downloadPath+"/"+name); + if(!file.exists()){ + file.createNewFile(); + } + //初始化属性 + tempFile = file; + //获取指定文件段的下载流 + InputStream in = conn.getDownloadStream(startPos, endPos); + if(in == null){ + return; + } + //随机访问文件流 + RandomAccessFile raf = new RandomAccessFile(tempFile, "rwd"); + //随机写文件的时候从哪个位置开始写 + raf.seek(startPos);//定位文件 + //开始写入 + byte[] buffer = new byte[1024]; + int length = -1; + while ((length = in.read(buffer)) != -1) { + raf.write(buffer, 0, length); + downloadSize += length; + } + raf.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + /** + * 修改后缀名称,并保存正确后缀名 + * @param name + * @return + */ + private String reSufferNameAndStore(String name){ + + sufferName = name.substring(name.lastIndexOf(".")); + name = name.substring(0,name.lastIndexOf("."))+".zj♥yy"; + return name; + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/FileDownloader.java b/group12/2258659044/zj-2017/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..cb84d148c7 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,74 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + +public class FileDownloader { + + String url; + + String downloadPath; + + DownloadListener listener; + + ConnectionManager cm; + + /*线程数目*/ + private final int threadNum = 5; + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + + Connection conn = null; + try { + + conn = cm.open(this.url); + int length = conn.getContentLength(); + //分配下载块 + int blockSize = length / threadNum; + DownloadThread[] threads = new DownloadThread[threadNum]; + for (int thread = 1; thread <= threadNum; thread++) { + int startIndex = (thread - 1) * blockSize; + int endIndex = thread * blockSize-1; + if (thread == threadNum) {//最后一个线程下载的长度 + endIndex = length; + } + DownloadThread thr = new DownloadThread(downloadPath,cm.open(this.url),startIndex,endIndex); + threads[thread-1] = thr; + thr.start(); + } + //判断所有线程是否下载完成 + new NotifyCaller(listener,threads,length).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + + public void setDownloadPath(String downloadPath) { + this.downloadPath = downloadPath; + } + +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/NotifyCaller.java b/group12/2258659044/zj-2017/src/com/coderising/download/NotifyCaller.java new file mode 100644 index 0000000000..03f4149688 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/NotifyCaller.java @@ -0,0 +1,100 @@ +package com.coderising.download; + +import java.io.File; +import java.text.DecimalFormat; + +import com.coderising.download.api.DownloadListener; + +public class NotifyCaller extends Thread{ + + /*监听器*/ + private DownloadListener listener; + + /*内存文件*/ + DownloadThread[] downloadThreads; + + /*文件总长度*/ + private int fileLength; + + private static final int HUNDRED = 100; + + public NotifyCaller(DownloadListener listener,DownloadThread[] downloadThreads,int fileLength){ + + this.listener = listener; + this.downloadThreads = downloadThreads; + this.fileLength = fileLength; + } + + @Override + public void run() { + + int i =1; + while(true){ + try { + Thread.sleep(5000); + if(HUNDRED == getPercentOfDownload()){ + rename(); + } + listener.notifyFinished(getPercentOfDownload(),getDownloadSpeed(5*i)); + i++; + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + /** + * 获取下载百分比 + * @return + */ + private int getPercentOfDownload(){ + + int sum = calculateDownloadSize(); + return (sum)/(fileLength/HUNDRED); + } + + /** + * 获取下载速度 + * @return + */ + private String getDownloadSpeed(int timeDiff){ + + float sum = calculateDownloadSize(); + DecimalFormat df = new DecimalFormat("0.000");//格式化小数 + String num = df.format((sum/((float)(1024*1024)*timeDiff)));//返回的是String类型 + if(num==null||num.isEmpty()){ + num = "0"; + } + return num+"M/s"; + } + + /** + * 计算已下载文件大小 + */ + private int calculateDownloadSize(){ + int sum = 0; + for (int i = 0; i < downloadThreads.length; i++) { + sum += downloadThreads[i].downloadSize; + } + return sum; + } + /** + * 重命名 + */ + private void rename(){ + + File tempFile = downloadThreads[0].tempFile; + String path = tempFile.getPath(); + String name = path.substring(0,path.lastIndexOf("."))+downloadThreads[0].sufferName; + File file = new File(name); + tempFile.renameTo(file); + + } + + public DownloadListener getListener() { + return listener; + } + public void setListener(DownloadListener listener) { + this.listener = listener; + } +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/api/Connection.java b/group12/2258659044/zj-2017/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..8ccb6a11bf --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/api/Connection.java @@ -0,0 +1,36 @@ +package com.coderising.download.api; + +import java.io.IOException; +import java.io.InputStream; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); + + /** + * 获取下载文件名称 + * @return + */ + public String getDownloadName(); + + /** + * 获取下载流 + * @return + */ + public InputStream getDownloadStream(int startPos, int endPos)throws IOException; +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionException.java b/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..c9bca99995 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,13 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 4776347926322882920L; + + public ConnectionException(){ + super(); + } +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionManager.java b/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..fb44ede457 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/api/DownloadListener.java b/group12/2258659044/zj-2017/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..82694051bd --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface DownloadListener { + + /** + * @param percent 下载百分比 + * @param downloadSpeed 下载速度,单位M/s + */ + public void notifyFinished(int percent,String downloadSpeed); +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionImpl.java b/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..ec8e503fe9 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,69 @@ +package com.coderising.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + /*http连接*/ + private HttpURLConnection httpConnection; + + /*下载文件名称*/ + private String fileName; + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + byte[] data = null; + InputStream is = getDownloadStream(startPos,endPos); + if(is !=null){ + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int length = -1; + while ((length = is.read(buffer)) != -1) { + baos.write(buffer, 0, length); + } + baos.flush(); + data = baos.toByteArray(); + } + return data; + } + + @Override + public InputStream getDownloadStream(int startPos, int endPos) throws IOException { + //请求服务器下载部分文件 指定文件的位置 + httpConnection.setRequestProperty("Range", "bytes="+startPos+"-"+endPos); + httpConnection.connect(); + if(httpConnection.getResponseCode()/100 == 2){ + return httpConnection.getInputStream(); + } + return null; + } + @Override + public int getContentLength() { + return httpConnection.getContentLength(); + } + + @Override + public void close() { + httpConnection.disconnect(); + } + + public void setHttpConnection(HttpURLConnection httpConnection) { + this.httpConnection = httpConnection; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + @Override + public String getDownloadName() { + return fileName; + } + +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..4996c21cc0 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,55 @@ +package com.coderising.download.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + URL remotUrl = null; + HttpURLConnection httpCon = null; + ConnectionImpl conn = new ConnectionImpl(); + try { + remotUrl = new URL(url); + httpCon = (HttpURLConnection)remotUrl.openConnection(); + httpCon.setRequestMethod("GET"); + httpCon.setConnectTimeout(6000); + httpCon.setReadTimeout(6000); + httpCon.setDoInput(true); + httpCon.setRequestProperty("connection", "keep-alive"); + httpCon.setRequestProperty("accept", "*/*"); + //设置Connection属性 + conn.setHttpConnection(httpCon); + conn.setFileName(getFileName(url)); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return conn; + } + + /** + * 获取文件名称 + * @param url + * @return + */ + private String getFileName(String url){ + + String fileName = ""; + if(url.contains("&")&&url.contains("=")){ + fileName = url.substring(url.lastIndexOf("=")+1); + }else{ + fileName = url.substring(url.lastIndexOf("/")+1); + } + return fileName; + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/LoginAction.java b/group12/2258659044/zj-2017/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..a3ce652047 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/Struts.java b/group12/2258659044/zj-2017/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..57f4f6d55e --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,201 @@ +package com.coderising.litestruts; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.coderising.litestruts.bean.Action; +import com.coderising.litestruts.bean.Result; + +public class Struts { + + private final static String ACTION = "action"; + private final static String RESULT = "result"; + private final static String NAME = "name"; + private final static String CLASS = "class"; + private final static String TYPE = "type"; + private final static String EXECUTE = "execute"; + + //Struts.xml描述的所有action信息 + private final static List actions; + //读取Struts.xml获取所有action相关信息 + static{ + String path = "src/com/coderising/litestruts/struts.xml"; + actions = readStrutsXml(path); + } + + public static View runAction(String actionName, + Map parameters) { + + View view = new View(); + Map viewMap = new HashMap(); + + //获取当前请求的action信息 + Action actionBean= getCurrentAction(actionName); + if(actionBean == null){ + return view; + } + try { + //创建实例获取属性 + String calssPath = actionBean.getClazz(); + Class clazz = Class.forName(calssPath); + Object instance = clazz.newInstance(); + Field[] fields = clazz.getDeclaredFields(); + String fieldName; + String methodName; + //调用set方法为属性赋值 + for (int i = 0; i < fields.length; i++) { + fieldName = fields[i].getName(); + if(parameters.containsKey(fieldName)){ + methodName = "set" + fieldName.substring(0, 1).toUpperCase() + + fieldName.substring(1); + Method method = clazz.getMethod(methodName, fields[i].getType()); + if(method != null){ + method.invoke(instance, parameters.get(fieldName)); + } + } + } + + //调用默认execute方法 + Method successMethos = clazz.getMethod(EXECUTE); + Object result = successMethos.invoke(instance); + // 调用get方法获取属性值 + for (int i = 0; i < fields.length; i++) { + fieldName = fields[i].getName(); + methodName = "get" + fieldName.substring(0, 1).toUpperCase() + + fieldName.substring(1); + Method method = clazz.getMethod(methodName); + if(method != null){ + Object value = method.invoke(instance); + viewMap.put(fieldName, value); + } + } + //封装view对象所需数据 + view.setParameters(viewMap); + List results = actionBean.getResults(); + for (int i = 0; i < results.size(); i++) { + if(results.get(i).getName().equals(result)){ + view.setJsp(results.get(i).getRedirectUrl()); + break; + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return view; + } + + /** + * 读取struts.xml文件 + * + * @param filePath + * :struts.xml路劲 + * @param actionName + * @return + */ + + private static List readStrutsXml(String filePath) { + + File xmlFile = new File(filePath); + Action action = null; + Result result = null; + List results = null; + List actions = new ArrayList(); + + try { + DocumentBuilder documentBuilder = DocumentBuilderFactory + .newInstance().newDocumentBuilder(); + Document document = documentBuilder.parse(xmlFile); + // 获取根节点 + Element element = document.getDocumentElement(); + NodeList actionNodes = element.getChildNodes(); + for (int i = 0; i < actionNodes.getLength(); i++) { + Node actionNode = actionNodes.item(i); + if (ACTION.equals(actionNode.getNodeName())) { + action = new Action(); + // 解析action标签 + NamedNodeMap actionNodeMap = actionNode.getAttributes(); + String actionName = getNodePropertyValue(actionNodeMap.getNamedItem(NAME)); + String claz = getNodePropertyValue(actionNodeMap.getNamedItem(CLASS)); + action.setName(actionName); + action.setClazz(claz); + // 解析result标签 + NodeList resultNodes = actionNode.getChildNodes(); + results = new ArrayList(); + for (int j = 0; j < resultNodes.getLength(); j++) { + Node resultNode = resultNodes.item(j); + if (RESULT.equals(resultNode.getNodeName())) { + result = new Result(); + NamedNodeMap resultNodeMap = resultNode.getAttributes(); + String resultName = getNodePropertyValue(resultNodeMap.getNamedItem(NAME)); + String resultType = getNodePropertyValue(resultNodeMap.getNamedItem(TYPE)); + String jspPath = resultNode.getTextContent(); + result.setName(resultName); + result.setType(resultType); + result.setRedirectUrl(jspPath); + results.add(result); + } + + } + action.setResults(results); + actions.add(action); + } + } + + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return actions; + } + + /** + * 获取当前action信息 + * @param actionName + * @return + */ + private static Action getCurrentAction(String actionName){ + + for (int i = 0; i < actions.size(); i++) { + if(actions.get(i).getName().equals(actionName)){ + return actions.get(i); + } + } + return null; + } + + /** + * 获取节点属性值 + * @param node + * @return + */ + private static String getNodePropertyValue(Node node){ + + if(node!=null){ + return node.getNodeValue(); + } + return null; + } + +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/View.java b/group12/2258659044/zj-2017/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..0c0b9d3b26 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Action.java b/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Action.java new file mode 100644 index 0000000000..1c8c26f6d0 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Action.java @@ -0,0 +1,45 @@ +package com.coderising.litestruts.bean; + +import java.util.List; + +/** + * struts.xml 对应action标签 + * @author zj + */ +public class Action { + + /*名称*/ + private String name; + + /*类全名名称*/ + private String clazz; + + /*result*/ + private List results; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClazz() { + return clazz; + } + + public void setClazz(String clazz) { + this.clazz = clazz; + } + + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } + + +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Result.java b/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Result.java new file mode 100644 index 0000000000..a595176c19 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/bean/Result.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts.bean; + +/** + * struts.xml 对应result标签 + * @author zj + */ +public class Result { + + /*名称*/ + private String name; + + /*跳转类型*/ + private String type; + + /*跳转路径*/ + private String redirectUrl; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getRedirectUrl() { + return redirectUrl; + } + + public void setRedirectUrl(String redirectUrl) { + this.redirectUrl = redirectUrl; + } + + +} diff --git a/group12/2258659044/zj-2017/src/com/coderising/litestruts/struts.xml b/group12/2258659044/zj-2017/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..4c6eeabbd4 --- /dev/null +++ b/group12/2258659044/zj-2017/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coding/basic/ArrayList.java b/group12/2258659044/zj-2017/src/com/coding/basic/ArrayList.java index a30b209281..f1fbf7e8b1 100644 --- a/group12/2258659044/zj-2017/src/com/coding/basic/ArrayList.java +++ b/group12/2258659044/zj-2017/src/com/coding/basic/ArrayList.java @@ -1,94 +1,100 @@ -package com.coding.basic; - -import java.util.NoSuchElementException; - -public class ArrayList implements List { - - private int size = 0; - /*扩容因子*/ - private static final int GENE = 10; - - private Object[] elementData = new Object[10]; - /*扩容引用*/ - private Object[] newElementData; - - public void add(Object o){ - grow(); - elementData[size] = o; - size ++; - } - public void add(int index, Object o){ - - if(index>size){ - throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); - } - grow(); - if(indexsize){ - throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); - } - return elementData[index]; - } - - public Object remove(int index){ - - Object o = elementData[index]; - System.arraycopy(elementData, index+1, elementData, index, size-(index+1)); - size --; - return o; - } - - public int size(){ - return size; - } - - /** - * 扩容,扩容因子为10 - */ - private void grow(){ - - if(size>=elementData.length){//长度不够需要扩容 - newElementData = new Object[size+GENE]; - System.arraycopy(elementData, 0, newElementData, 0, elementData.length); - elementData = newElementData; - } - } - - - public Iterator iterator(){ - - return new Itr(); - } - - private class Itr implements Iterator{ - - int cursor; - @Override - public boolean hasNext() { - return cursor != ArrayList.this.size; - } - - @Override - public Object next() { - - int i = this.cursor; - if (i >= ArrayList.this.size){ - throw new NoSuchElementException(); - } - this.cursor = (i + 1); - return ArrayList.this.elementData[i]; - } - - } -} +package com.coding.basic; + +import java.util.NoSuchElementException; + +public class ArrayList implements List { + + private int size = 0; + /*扩容因子*/ + private static final int GENE = 10; + + private Object[] elementData = new Object[10]; + /*扩容引用*/ + private Object[] newElementData; + + public void add(Object o){ + grow(); + elementData[size] = o; + size ++; + } + public void add(int index, Object o){ + + if(index<0||index>size){ + throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); + } + grow(); + if(indexsize){ + throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); + } + return elementData[index]; + } + + public Object remove(int index){ + + Object o = elementData[index]; + System.arraycopy(elementData, index+1, elementData, index, size-(index+1)); + size --; + return o; + } + + public int size(){ + return size; + } + + public Object[] toArray(){ + Object[] objArr = new Object[size]; + System.arraycopy(elementData, 0, objArr, 0, size); + return objArr; + } + + /** + * 扩容,扩容因子为10 + */ + private void grow(){ + + if(size>=elementData.length){//长度不够需要扩容 + newElementData = new Object[size+GENE]; + System.arraycopy(elementData, 0, newElementData, 0, elementData.length); + elementData = newElementData; + } + } + + + public Iterator iterator(){ + + return new Itr(); + } + + private class Itr implements Iterator{ + + int cursor; + @Override + public boolean hasNext() { + return cursor != ArrayList.this.size; + } + + @Override + public Object next() { + + int i = this.cursor; + if (i >= ArrayList.this.size){ + throw new NoSuchElementException(); + } + this.cursor = (i + 1); + return ArrayList.this.elementData[i]; + } + + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/com/coding/basic/LinkedList.java b/group12/2258659044/zj-2017/src/com/coding/basic/LinkedList.java index 460298ff56..3bf26a1a1c 100644 --- a/group12/2258659044/zj-2017/src/com/coding/basic/LinkedList.java +++ b/group12/2258659044/zj-2017/src/com/coding/basic/LinkedList.java @@ -1,137 +1,271 @@ -package com.coding.basic; - -import java.util.NoSuchElementException; - -public class LinkedList implements List { - - private Node head; - - private int size = 0; - - public void add(Object o){ - - Node addNode = new Node(); - addNode.data = o; - if(size==0){ - head = addNode; - }else{ - //获取最后一个节点 - Node lastNode = getPointNode(size-1); - lastNode.next = addNode; - } - size++; - } - public void add(int index , Object o){ - - Node addNode = new Node(); - addNode.data = o; - if(index == 0){ - addFirst(o); - return; - } - if(index == size){ - Node lastNode = getPointNode(size-1); - lastNode.next = addNode; - }else{ - Node pointNode = getPointNode(index); - Node prePointNode = getPointNode(index-1); - prePointNode.next = addNode; - addNode.next = pointNode; - } - size ++; - } - public Object get(int index){ - - Node node = getPointNode(index); - return node.data; - } - - public Object remove(int index){ - - Node pointNode = getPointNode(index); - Node nextPointNode = getPointNode(index+1); - if(index ==0){ - head = nextPointNode; - }else{ - Node prePointNode = getPointNode(index-1); - prePointNode.next = nextPointNode; - } - size --; - return pointNode.data; - } - - public int size(){ - return size; - } - - public void addFirst(Object o){ - - Node secondNode = head; - head = new Node(); - head.data = o; - if(size>0){ - head.next = secondNode; - } - size ++; - } - - public void addLast(Object o){ - add(o); - } - - public Object removeFirst(){ - - return remove(0); - } - - public Object removeLast(){ - - return remove(size-1); - } - public Iterator iterator(){ - return new Itr(); - } - - private class Itr implements Iterator{ - - int cursor; - @Override - public boolean hasNext() { - return cursor != LinkedList.this.size; - } - - @Override - public Object next() { - - int i = this.cursor; - if (i >= LinkedList.this.size){ - throw new NoSuchElementException(); - } - this.cursor = (i + 1); - return LinkedList.this.get(i); - } - - } - - /** - * 获取指定的节点 - * @return - */ - private Node getPointNode(int index){ - - if(index>size){ - throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size+""); - } - Node node = head; - for (int i = 0; i < index; i++) { - node = node.next; - } - return node; - } - - private static class Node{ - Object data; - Node next; - - } +package com.coding.basic; + +import java.util.NoSuchElementException; + +public class LinkedList implements List { + + private Node head; + + private int size = 0; + + public void add(Object o){ + + Node addNode = new Node(); + addNode.data = o; + if(size==0){ + head = addNode; + }else{ + //获取最后一个节点 + Node lastNode = getPointNode(size-1); + lastNode.next = addNode; + } + size++; + } + public void add(int index , Object o){ + + Node addNode = new Node(); + addNode.data = o; + if(index == 0){ //添加头结点 + addFirst(o); + }else if(index == size){//添加尾节点 + addLast(o); + }else{//在投节点与尾部添加节点 + Node prePointNode = getPointNode(index-1); + Node pointNode = prePointNode.next; + prePointNode.next = addNode; + addNode.next = pointNode; + size ++; + } + } + public Object get(int index){ + + Node node = getPointNode(index); + return node.data; + } + + public Object remove(int index){ + + Node pointNode = getPointNode(index); + Node nextPointNode = pointNode.next; + if(index ==0){ + head = nextPointNode; + }else{ + Node prePointNode = getPointNode(index-1); + prePointNode.next = nextPointNode; + } + size --; + return pointNode.data; + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + + Node secondNode = head; + head = new Node(); + head.data = o; + if(size>0){ + head.next = secondNode; + } + size ++; + } + + public void addLast(Object o){ + add(o); + } + + public Object removeFirst(){ + + return remove(0); + } + + public Object removeLast(){ + + return remove(size-1); + } + public Iterator iterator(){ + return new Itr(); + } + + private class Itr implements Iterator{ + + int cursor; + @Override + public boolean hasNext() { + return cursor != LinkedList.this.size; + } + + @Override + public Object next() { + + int i = this.cursor; + if (i >= LinkedList.this.size){ + throw new NoSuchElementException(); + } + this.cursor = (i + 1); + return LinkedList.this.get(i); + } + + } + + /** + * 获取指定的节点 + * @return + */ + private Node getPointNode(int index){ + + if(index<0||index>size){ + throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size+""); + } + Node node = head; + for (int i = 0; i < index; i++) { + node = node.next; + } + return node; + } + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + Stack stack = new Stack(); + Node node; + //缓存原链表数据 + for (node = head; node!=null;node = node.next) { + stack.push(node.data); + } + //重新赋值 + for (node = head; node!=null;node = node.next) { + node.data = stack.pop(); + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf(){ + int newSize = size/2; + head = getPointNode(newSize); + size = size%2>0?newSize+1:newSize; + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + if(i==0){ + if(length101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + int[] array = new int[list.size()]; + for (int i = 0; i < array.length; i++) { + array[i] = (int) get((int)list.get(i)); + } + return array; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + + public void subtract(LinkedList list){ + for (int i = 0; i < size; i++) { + for (int j = 0; j < list.size(); j++) { + if(get(i).equals(list.get(j))){ + remove(i); + i--; + } + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + for (int i = 0; i < size-1; i++) { + if(get(i).equals(get(i+1))){ + remove(i); + i --; + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + for (int i = 0; i < size; i++) { + if((int)get(i)>min&&(int)get(i) params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} \ No newline at end of file diff --git a/group12/2258659044/zj-2017/src/test/com/coding/basic/LinkedListTest.java b/group12/2258659044/zj-2017/src/test/com/coding/basic/LinkedListTest.java index 3a5ff822ad..c43e66abf9 100644 --- a/group12/2258659044/zj-2017/src/test/com/coding/basic/LinkedListTest.java +++ b/group12/2258659044/zj-2017/src/test/com/coding/basic/LinkedListTest.java @@ -1,109 +1,258 @@ -package test.com.coding.basic; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.coding.basic.Iterator; -import com.coding.basic.LinkedList; - -public class LinkedListTest { - - LinkedList ls ; - @Before - public void setup() { - ls = new LinkedList(); - } - - /** - * 测试一个参数的add方法 - * ArrayList当数据超过10时进行第一次扩容 - */ - @Test - public void add(){ - - ls.add(3); - ls.add("a"); - for (int i = 0; i < 10; i++) { - ls.add(i); - } - Assert.assertEquals(ls.size(), 12); - Assert.assertEquals(ls.get(1), "a"); - } - - /** - * 两个参数的add方法 - */ - @Test//(expected = IndexOutOfBoundsException.class) - public void add4ToPramter(){ - - ls.add(0, 0); - ls.add(1,1); - ls.add(2, 2); - ls.add(3,3); - for (int i = 0; i < 10; i++) { - ls.add(3,i); - } - Assert.assertEquals(ls.size(), 14); - Assert.assertEquals(ls.get(3), 9); - Assert.assertEquals(ls.get(13), 3); - //打开下面操作抛出异常 - //ls.add(15, "a"); - } - - /** - * get(i) - */ - @Test//(expected = IndexOutOfBoundsException.class) - public void get(){ - - for (int i = 0; i < 10; i++) { - ls.add(i); - } - - Assert.assertEquals(ls.get(9), 9); - //打开下面操作抛出异常 - //ls.get(12); - } - - @Test - public void remove(){ - - for (int i = 0; i < 10; i++) { - ls.add(i); - } - Assert.assertEquals(ls.remove(5),5); - Assert.assertEquals(ls.size(),9); - Assert.assertEquals(ls.remove(8),9); - Assert.assertEquals(ls.size(),8); - } - - @Test - public void size(){ - - Assert.assertEquals(ls.size(),0); - ls.add("a"); - Assert.assertEquals(ls.size(),1); - ls.add(0,0); - Assert.assertEquals(ls.size(),2); - ls.remove(0); - Assert.assertEquals(ls.size(),1); - - } - - @Test//(expected = NoSuchElementException.class) - public void iterator(){ - - for (int i = 0; i < 10; i++) { - ls.add(i); - } - Iterator it = ls.iterator(); - Assert.assertEquals(it.hasNext(),true); - for (int i = 0; i < 10; i++) { - it.next(); - } - Assert.assertEquals(it.hasNext(),false); - //打开下面操作抛出异常 - //it.next(); - } -} +package test.com.coding.basic; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.coding.basic.Iterator; +import com.coding.basic.LinkedList; + +public class LinkedListTest { + + LinkedList ls ; + @Before + public void setup() { + ls = new LinkedList(); + } + + /** + * 测试一个参数的add方法 + * ArrayList当数据超过10时进行第一次扩容 + */ + @Test + public void add(){ + + ls.add(3); + ls.add("a"); + for (int i = 0; i < 10; i++) { + ls.add(i); + } + Assert.assertEquals(ls.size(), 12); + Assert.assertEquals(ls.get(1), "a"); + } + + /** + * 两个参数的add方法 + */ + @Test//(expected = IndexOutOfBoundsException.class) + public void add4ToPramter(){ + + ls.add(0, 0); + ls.add(1,1); + ls.add(2, 2); + ls.add(3,3); + for (int i = 0; i < 10; i++) { + ls.add(3,i); + } + Assert.assertEquals(ls.size(), 14); + Assert.assertEquals(ls.get(3), 9); + Assert.assertEquals(ls.get(13), 3); + //打开下面操作抛出异常 + //ls.add(15, "a"); + } + + /** + * get(i) + */ + @Test//(expected = IndexOutOfBoundsException.class) + public void get(){ + + for (int i = 0; i < 10; i++) { + ls.add(i); + } + + Assert.assertEquals(ls.get(9), 9); + //打开下面操作抛出异常 + //ls.get(12); + } + + @Test + public void remove(){ + + for (int i = 0; i < 10; i++) { + ls.add(i); + } + Assert.assertEquals(ls.remove(5),5); + Assert.assertEquals(ls.size(),9); + Assert.assertEquals(ls.remove(8),9); + Assert.assertEquals(ls.size(),8); + } + + @Test + public void size(){ + + Assert.assertEquals(ls.size(),0); + ls.add("a"); + Assert.assertEquals(ls.size(),1); + ls.add(0,0); + Assert.assertEquals(ls.size(),2); + ls.remove(0); + Assert.assertEquals(ls.size(),1); + + } + + @Test//(expected = NoSuchElementException.class) + public void iterator(){ + + for (int i = 0; i < 10; i++) { + ls.add(i); + } + Iterator it = ls.iterator(); + Assert.assertEquals(it.hasNext(),true); + for (int i = 0; i < 10; i++) { + it.next(); + } + Assert.assertEquals(it.hasNext(),false); + //打开下面操作抛出异常 + //it.next(); + } + + @Test + public void testReverse(){ + + ls.add(3); + ls.add(7); + ls.add(10); + ls.add(8); + ls.reverse(); + int[] expected = {8,10,7,3}; + for (int i = 0; i < ls.size(); i++) { + Assert.assertEquals(expected[i], ls.get(i)); + } + } + + public void testRemoveFirstHalf(){ + + ls.add(2); + ls.add(5); + ls.add(7); + ls.add(8); + ls.add(10); + int[] expected = {7,8,10}; + ls.removeFirstHalf(); + for (int i = 0; i < ls.size(); i++) { + Assert.assertEquals(ls.get(i), expected[i]); + } + + } + + @Test + public void testRemove(){ + ls.add(2); + ls.add(5); + ls.add(7); + ls.add(8); + ls.add(10); + + ls.remove(0, 1); + int[] expected = {5,7,8,10}; + exceptResult(ls,expected); + + ls.remove(3,1); + int[] expected1 = {5,7,8}; + exceptResult(ls,expected1); + + ls.add(9); + ls.remove(2,8); + int[] expected2 = {5,7}; + exceptResult(ls,expected2); + + ls.remove(0,9); + int[] expected3 = {}; + exceptResult(ls,expected3); + + } + + @Test + public void testGetElements(){ + ls.add(11);ls.add(101); + ls.add(201);ls.add(301); + ls.add(401);ls.add(501); + ls.add(601);ls.add(701); + LinkedList list = new LinkedList(); + list.add(1);list.add(3); + list.add(4);list.add(6); + int[] exceptArr = {101,301,401,601}; + int[] actual= ls.getElements(list); + for (int i = 0; i < actual.length; i++) { + Assert.assertEquals(exceptArr[i],actual[i]); + } + Assert.assertEquals(exceptArr.length,actual.length); + } + + @Test + public void testSubtract(){ + + ls.add(2); + ls.add(5); + ls.add(7); + ls.add(8); + ls.add(10); + + LinkedList list = new LinkedList(); + list.add(2); + list.add(5); + + int[] exceptArr = {7,8,10}; + ls.subtract(list); + exceptResult(ls,exceptArr); + + } + + @Test + public void testRemoveDuplicateValues(){ + + ls.add(2); + ls.add(5); + ls.add(5); + ls.add(5); + ls.add(8); + ls.add(8); + ls.removeDuplicateValues(); + int[] exceptArr = {2,5,8}; + exceptResult(ls,exceptArr); + } + + @Test + public void testRemoveRange(){ + + ls.add(2); + ls.add(5); + ls.add(7); + ls.add(8); + ls.add(10); + + ls.removeRange(0, 7); + int[] exceptArr = {7,8,10}; + exceptResult(ls,exceptArr); + } + + @Test + public void testIntersection(){ + + ls.add(-2); + ls.add(-1); + ls.add(0); + ls.add(3); + ls.add(5); + + LinkedList list = new LinkedList(); + list.add(-1); + list.add(0); + list.add(5); + list.add(9); + + LinkedList newList = ls.intersection(list); + + int[] exceptArr = {-1,0,5}; + exceptResult(newList,exceptArr); + } + + private void exceptResult(LinkedList ls,int[] exceptArr){ + + Assert.assertEquals(ls.size(), exceptArr.length); + for (int i = 0; i < exceptArr.length; i++) { + Assert.assertEquals(exceptArr[i],ls.get(i)); + } + } +} diff --git a/group12/2319021847/homework1/com/code/basic/ArrayList.java b/group12/2319021847/homework1/com/code/basic/ArrayList.java new file mode 100644 index 0000000000..942bce6c2a --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/ArrayList.java @@ -0,0 +1,106 @@ +package com.coding.basic; + +public class ArrayList implements List{ + + private int size = 0; + private Object[] elements; + + public ArrayList() { + this.elements = new Object[5]; + } + + public ArrayList(int size) { + this.elements = new Object[size]; + } + public void add(Object o) { + // TODO Auto-generated method stub + if(isFull()) + { + resize(); + } + this.elements[this.size] = o; + this.size++; + } + public boolean isFull () + { + if(this.size == this.elements.length) + { + return true; + } + + return false; + } + + public void resize() + { + Object[] newElements = new Object[this.elements.length*2]; + System.arraycopy(elements, 0, newElements, 0, elements.length); + this.elements = newElements; + newElements = null; + } + public void add(int index, Object o) { + // TODO Auto-generated method stub + rangeCheck(index); + if(isFull()) + { + resize(); + } + System.arraycopy(elements, index, elements, index+1,size-index); + this.elements[index] = o; + size++; + } + void rangeCheck(int index) + { + if(index > size || index < 0) + { + throw new IndexOutOfBoundsException("±Խ"); + } + } + public Object get(int index) { + // TODO Auto-generated method stub + rangeCheck(index); + return elements[index]; + } + + public Object remove(int index) { + // TODO Auto-generated method stub + rangeCheck(index); + Object elem = elements[index]; + System.arraycopy(elements, index+1, elements, index, size-index-1); + size--; + elements[size] = null; + return elem; + } + + public int size() { + // TODO Auto-generated method stub + return this.size; + } + public com.coding.basic.Iterator Iterator () + { + return new Itr(); + } + public class Itr implements com.coding.basic.Iterator{ + int cur = 0; + public boolean hasNext() { + // TODO Auto-generated method stub + if(size==cur) + { + return false; + } + return true; + } + + public Object next() { + // TODO Auto-generated method stub + int i = cur; + if(i < elements.length) + { + cur = i+1; + return elements[i]; + } + return null; + } + + } +} diff --git a/group12/2319021847/homework1/com/code/basic/BinaryTreeNode.java b/group12/2319021847/homework1/com/code/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..2e026b47b6 --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/BinaryTreeNode.java @@ -0,0 +1,53 @@ +package com.coding.basic; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private BinaryTreeNode root; + + public BinaryTreeNode(Object o){ + this.data = o; + this.left = null; + this.right = null; + } + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(BinaryTreeNode root, Object o){ + BinaryTreeNode current = root; + BinaryTreeNode node = new BinaryTreeNode(o); + if(current == null) + { + current = node; + } + else if(((Integer)current.getData()).intValue() < ((Integer)o).intValue()) + { + insert(current.getLeft(),o); + } + else if(((Integer)current.getData()).intValue() >= ((Integer)o).intValue()) + { + insert(current.getRight(),o); + } + + return node; + } + +} diff --git a/group12/2319021847/homework1/com/code/basic/Iterator.java b/group12/2319021847/homework1/com/code/basic/Iterator.java new file mode 100644 index 0000000000..f6ecde73bf --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/Iterator.java @@ -0,0 +1,6 @@ +package com.coding.basic; + +public interface Iterator { + boolean hasNext(); + Object next(); +} diff --git a/group12/2319021847/homework1/com/code/basic/LinkList.java b/group12/2319021847/homework1/com/code/basic/LinkList.java new file mode 100644 index 0000000000..9f759f9088 --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/LinkList.java @@ -0,0 +1,86 @@ +package com.coding.basic; + +public class LinkList implements List{ + + private LinkNode head; + // TODO Auto-generated method stub + private int size; + + public LinkList() + { + this.head = null; + this.size = 0; + } + public void add(Object o) { + // TODO Auto-generated method stub + LinkNode currPtr = this.head; + if(this.head == null) + { + this.head = new LinkNode(o, this.head ,null); + } + while(currPtr != null) + { + currPtr = currPtr.getNext(); + } + currPtr.setNext(new LinkNode(o, currPtr, null)); + size++; + } + + public void add(int index, Object o) { + // TODO Auto-generated method stub + LinkNode currPtr = this.head; + if(index < 0 || index > size) + throw new IndexOutOfBoundsException("±Խ"); + int i = 0; + if(index == 0) + { + LinkNode node = new LinkNode(o,currPtr,currPtr.getPrv()); + currPtr.getNext().setPrv(node); + currPtr = node; + } + while(i < index) + { + currPtr = currPtr.getNext(); + i++; + } + LinkNode node = new LinkNode(o,currPtr.getPrv(),currPtr); + currPtr.getPrv().setNext(node); + currPtr.setPrv(node); + size++; + } + + public Object get(int index) { + if(index < 0 || index > size) + throw new IndexOutOfBoundsException("±Խ"); + int i = 0; + LinkNode currPtr = this.head; + while(i < index) + { + currPtr = currPtr.getNext(); + i++; + } + + return currPtr.getData(); + } + + public Object remove(int index) { + // TODO Auto-generated method stub + int i = 0; + LinkNode currPtr = this.head; + while(i < index) + { + currPtr = currPtr.getNext(); + i++; + } + currPtr.getNext().setPrv(currPtr.getPrv()); + currPtr.getPrv().setNext( currPtr.getNext()); + size--; + return currPtr.getData(); + } + + public int size() { + // TODO Auto-generated method stub + return size; + } + +} diff --git a/group12/2319021847/homework1/com/code/basic/LinkNode.java b/group12/2319021847/homework1/com/code/basic/LinkNode.java new file mode 100644 index 0000000000..1452dcc42b --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/LinkNode.java @@ -0,0 +1,46 @@ +package com.coding.basic; + +public class LinkNode { + private LinkNode pNextPtr; + private LinkNode pPrvPtr; + private Object ndata; + + public LinkNode () + { + this.pNextPtr=null; + this.pPrvPtr=null; + this.ndata=null; + } + + public LinkNode (Object o, LinkNode pPrvPtr, LinkNode pNextPtr) + { + this.pNextPtr=null; + this.pPrvPtr=null; + this.ndata=null; + } + + public void setNext(LinkNode node) + { + this.pNextPtr = node; + } + + public void setPrv(LinkNode node) + { + this.pPrvPtr = node; + } + + public LinkNode getNext() + { + return this.pNextPtr; + } + + public LinkNode getPrv() + { + return this.pPrvPtr; + } + public Object getData() + { + return this.ndata; + } + +} diff --git a/group12/2319021847/homework1/com/code/basic/List.java b/group12/2319021847/homework1/com/code/basic/List.java new file mode 100644 index 0000000000..8360496919 --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/List.java @@ -0,0 +1,14 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + + public void add(int index, Object o); + + public Object get(int index); + + public Object remove(int index); + + public int size(); + +} diff --git a/group12/2319021847/homework1/com/code/basic/Queue.java b/group12/2319021847/homework1/com/code/basic/Queue.java new file mode 100644 index 0000000000..4dac2bfc22 --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/Queue.java @@ -0,0 +1,70 @@ +package com.coding.basic; + +public class Queue { + private int size; + + private int head; + + private int tail; + + private Object[] queue; + + public Queue() + { + this.size = 0; + this.head = 0; + this.tail = 0; + } + + public void enQueue(Object o) { + if(isFull()) + { + resize(); + } + int newtail = (head+size)%queue.length; + queue[newtail] = o; + size++; + } + + public Object deQueue() { + if(isEmpty()) + { + return null; + } + Object oldHead = queue[head]; + head = (head-1)%queue.length; + size--; + return oldHead; + } + + public int getHead(){ + return head; + } + + public int getTail(){ + return tail; + } + + + public boolean isEmpty() { + return size == 0; + } + + public int size() { + int diff = tail - head; + return diff; + } + + // + public boolean isFull(){ + return size == queue.length; + } + + + public void resize(){ + Object[] newQueue = new Object[2*(queue.length)]; + System.arraycopy(queue, 0, newQueue, 0, size); + this.queue = newQueue; + newQueue = null; + } +} diff --git a/group12/2319021847/homework1/com/code/basic/Stack.java b/group12/2319021847/homework1/com/code/basic/Stack.java new file mode 100644 index 0000000000..370197cb32 --- /dev/null +++ b/group12/2319021847/homework1/com/code/basic/Stack.java @@ -0,0 +1,45 @@ +package com.coding.basic; + + + +public class Stack { + private Object[] elements; + private int size; + + + public Stack() + { + this.size = 0; + this.elements = new Object[10]; + } + public void push(Object o){ + if(o == null) + return; + size++; + elements[size-1] = o; + } + + public Object pop(){ + if(isEmpty()) + { + return null; + } + Object pop = elements[size-1]; + size--; + return pop; + } + + public Object peek(){ + if(isEmpty()) + { + return null; + } + return elements[size-1]; + } + public boolean isEmpty(){ + return size < 1; + } + public int size(){ + return size; + } +} \ No newline at end of file diff --git a/group12/247565311/week1/ArrayList.java b/group12/247565311/week1/ArrayList.java index c2643af683..794630a76c 100644 --- a/group12/247565311/week1/ArrayList.java +++ b/group12/247565311/week1/ArrayList.java @@ -1,11 +1,6 @@ package week1; -import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - public class ArrayList implements List { private int size=0,offset=10; @@ -19,8 +14,7 @@ public ArrayList(int arg0){ data = new Object[size]; } @Override - public boolean add(E arg0) { - if(arg0 == null) return false; + public void add(Object arg0) { size += 1; int leng = data.length; if(size>leng){ @@ -30,8 +24,7 @@ public boolean add(E arg0) { } data = newdata; } - data[leng] = arg0; - return true; + data[size-1] = arg0; } @Override @@ -53,7 +46,6 @@ public void add(int arg0, E arg1) { return ; } - @Override public boolean addAll(Collection arg0) { if (arg0 == null) return false; int leng = data.length,newobjnum = arg0.size(),lastsize=size; @@ -72,7 +64,6 @@ public boolean addAll(Collection arg0) { return true; } - @Override public boolean addAll(int arg0, Collection arg1) { int newobjnum = arg1.size(),lastsize = size; if(arg1 == null || arg0>size+1 || 0>arg0 || newobjnum==0) return false; @@ -96,13 +87,11 @@ public boolean addAll(int arg0, Collection arg1) { return true; } - @Override public void clear() { size=0; data = new Object[offset]; } - @Override public boolean contains(Object arg0) { for(Object e:data){ if(e.equals(arg0)) return true; @@ -110,7 +99,6 @@ public boolean contains(Object arg0) { return false; } - @Override public boolean containsAll(Collection arg0) { for(Object o:arg0){ if(!this.contains(o)) return false; @@ -124,7 +112,6 @@ public E get(int arg0) { return null; } - @Override public int indexOf(Object arg0) { for(int i=0;i-1;i--){ if(this.data[i].equals(arg0)) return i; @@ -144,25 +130,11 @@ public int lastIndexOf(Object arg0) { return -1; } - @Override public Iterator iterator() { return null; } - @Override - public ListIterator listIterator() { - - return null; - } - - @Override - public ListIterator listIterator(int arg0) { - - return null; - } - - @Override public boolean remove(Object arg0) { for(int i=0;i arg0) { int toberemovednums = arg0.size(); if(!this.containsAll(arg0)) return false; @@ -197,13 +168,6 @@ public boolean removeAll(Collection arg0) { return true; } - @Override - public boolean retainAll(Collection arg0) { - // what does this mean? - return false; - } - - @Override public E set(int arg0, E arg1) { if(arg0<0||arg0>this.size-1) return null; this.data[arg0] = arg1; @@ -215,7 +179,6 @@ public int size() { return this.size; } - @Override public List subList(int arg0, int arg1) { if(arg0>=arg1 || arg0<0 || arg1>this.size-1) return null; List res = new ArrayList(); @@ -228,22 +191,30 @@ public List subList(int arg0, int arg1) { return null; } ////////////////////////////////////////////// - @Override public Object[] toArray() { if(this.size == 0) return null; Object[] res = new Object[this.size]; for(int i=0;i T[] toArray(T[] arg0) { T[] res = (T[])(new Object[this.size]); for(int i=0;i { - private LinkedList data = new LinkedList(); - private int size = 0; - - - public Deque(){ - - } - public Deque(int arg0){ - data = new LinkedList(arg0); - } - public boolean push(E arg0){ - data.add(data.size(),arg0); - size += 1; - return true; - } - public E pop(){ - size -= 1; - E res = data.get(0); - data.remove(0); - return res; - } - public E peek(){ - return data.get(0); - } - public int size(){ - return this.size; - } - public boolean isEmpty(){ - return this.size==0; - } - -} diff --git a/group12/247565311/week1/Iterator.java b/group12/247565311/week1/Iterator.java new file mode 100644 index 0000000000..7967f1827e --- /dev/null +++ b/group12/247565311/week1/Iterator.java @@ -0,0 +1,6 @@ +package week1; + +public interface Iterator { + public boolean hasNext(); + public E next(); +} diff --git a/group12/247565311/week1/Link.java b/group12/247565311/week1/Link.java deleted file mode 100644 index e2910e53d3..0000000000 --- a/group12/247565311/week1/Link.java +++ /dev/null @@ -1,5 +0,0 @@ -package week1; - -public class Link { - -} diff --git a/group12/247565311/week1/LinkedList.java b/group12/247565311/week1/LinkedList.java index c3f0ca2eb8..0b74925cbe 100644 --- a/group12/247565311/week1/LinkedList.java +++ b/group12/247565311/week1/LinkedList.java @@ -1,11 +1,8 @@ package week1; import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -public class LinkedList implements List,Cloneable { +public class LinkedList implements List { private Node head = null; private Node tail = null; private int size = 0; @@ -40,14 +37,13 @@ public Object clone(){ return clone; } @Override - public boolean add(Object val) { + public void add(Object val) { Node n = new Node(val); n.next = tail; n.ahead = tail.ahead; tail.ahead.next = n; tail.ahead = n; size += 1; - return true; } @Override @@ -64,7 +60,6 @@ public void add(int arg0, E arg1) { size += 1; } - @Override public boolean addAll(Collection arg0) { for(E o:arg0){ this.add(o); @@ -72,7 +67,6 @@ public boolean addAll(Collection arg0) { return true; } - @Override public boolean addAll(int arg0, Collection arg1) { for(E e:arg1){ this.add(arg0,e); @@ -81,7 +75,6 @@ public boolean addAll(int arg0, Collection arg1) { return true; } - @Override public void clear() { head = new Node(null); tail = new Node(null); @@ -90,7 +83,6 @@ public void clear() { size = 0; } - @Override public boolean contains(Object arg0) { boolean flag = arg0==null; Node n = head; @@ -105,7 +97,6 @@ public boolean contains(Object arg0) { return false; } - @Override public boolean containsAll(Collection arg0) { for(Object e:arg0){ if(!this.contains(e)) return false; @@ -126,9 +117,8 @@ public E get(int arg0) { return res; } - @Override public int indexOf(Object arg0) { - boolean flag = arg0 == null; + boolean flag = (arg0 == null); Node n=head; for(int i=0;i iterator() { return null; } - @Override public int lastIndexOf(Object arg0) { boolean flag = arg0==null; Node n = tail; @@ -167,19 +154,6 @@ public int lastIndexOf(Object arg0) { return -1; } - @Override - public ListIterator listIterator() { - - return null; - } - - @Override - public ListIterator listIterator(int arg0) { - - return null; - } - - @Override public boolean remove(Object arg0) { Node n = head; int index = this.indexOf(arg0); @@ -206,7 +180,6 @@ public E remove(int arg0) { return (E)(d.val); } - @Override public boolean removeAll(Collection arg0) { for(Object o:arg0){ if(!this.remove(o)) return false; @@ -214,13 +187,11 @@ public boolean removeAll(Collection arg0) { return true; } - @Override public boolean retainAll(Collection arg0) { // ? return false; } - @Override public E set(int arg0, E arg1) { if(arg0<0 || arg0>size-1) return null; Node n=head; @@ -236,13 +207,6 @@ public int size() { return size; } - @Override - public List subList(int arg0, int arg1) { - - return null; - } - - @Override public Object[] toArray() { Object[]res = new Object[size]; Node n = head; @@ -253,14 +217,26 @@ public Object[] toArray() { return res; } - @Override public T[] toArray(T[] arg0) { - - return null; + T[]res = (T[]) new Object[size]; + Node n = head; + for(int i=0;i extends Iterator{ + public void add(Object o); + public void add(int index, E o); + public E get(int index); + public E remove(int index); + public int size(); +} diff --git a/group12/247565311/week1/Queue.java b/group12/247565311/week1/Queue.java new file mode 100644 index 0000000000..78f25cb826 --- /dev/null +++ b/group12/247565311/week1/Queue.java @@ -0,0 +1,18 @@ +package week1; +public class Queue { + private LinkedList data = new LinkedList(); + public void enQueue(E arg0){ + data.add(data.size(),arg0); + } + public E deQueue(){ + E res = data.get(0); + data.remove(0); + return res; + } + public int size(){ + return data.size(); + } + public boolean isEmpty(){ + return data.isEmpty(); + } +} diff --git a/group12/247565311/week1/Stack.java b/group12/247565311/week1/Stack.java index 5672274d81..5dcccc5fca 100644 --- a/group12/247565311/week1/Stack.java +++ b/group12/247565311/week1/Stack.java @@ -1,39 +1,28 @@ package week1; -import java.util.List; +import week1.List; public class Stack { - private List data = new ArrayList(); - private int size = 0; - - public Stack(){ - - } - - public Stack(int arg0){ - if(arg0 < 0) arg0 = 0; - size = arg0; - data = new ArrayList(size); - - } + private ArrayList data = new ArrayList(); public boolean isEmpty(){ - return size==0; + return data.isEmpty(); + } + public int size(){ + return data.size(); } public boolean push(E arg0){ - size += 1; data.add(arg0); return true; } public E pop(){ if(this.isEmpty()) return null; - size -= 1; - E res = data.get(size); - data.remove(size); + E res = data.get(data.size()-1); + data.remove(data.size()-1); return res; } public E peek(){ if(this.isEmpty()) return null; - E res = data.get(size-1); + E res = data.get(data.size()-1); return res; } } diff --git a/group12/247565311/week2/ArrayUtil.java b/group12/247565311/week2/ArrayUtil.java new file mode 100644 index 0000000000..00bab36625 --- /dev/null +++ b/group12/247565311/week2/ArrayUtil.java @@ -0,0 +1,206 @@ +package week2; +import week1.ArrayList; + +public class ArrayUtil { + + /** + * һa , Ըֵû + 磺 a = [7, 9 , 30, 3] , ûΪ [3, 30, 9,7] + a = [7, 9, 30, 3, 4] , ûΪ [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ // time :O(n) + int leno = origin.length; + for(int i=0;i=len1){ + temparray[temp] = array2[p2]; + p2 += 1; + continue; + } + if(p2>=len2){ + temparray[temp] = array1[p1]; + p1 += 1; + continue; + } + if(array1[p1] > array2[p2]){ + temparray[temp] = array2[p2]; + p2 += 1; + }else{ + temparray[temp] = array1[p1]; + p1 += 1; + } + } + temp = 0; + for(int i=1;i data = new ArrayList(); + data.add(llast); + data.add(last); + while(last+llast li = new ArrayList(); + int cur = 2; + while(cur li = null,resli = new ArrayList(); + for(int i=6;i getAllElem(int arg0){ + ArrayList res = new ArrayList(); + for(int i=1;iparameters){ + if(actionName == null || parameters == null) return null; + List actions = null; + try { + File xmlfile = new File("D:\\5Java\\coding2017\\group12\\247565311\\week2\\struts.xml"); + Document doc = new SAXReader().read(xmlfile); + Element root = doc.getRootElement(); + actions = root.elements(); + } catch (DocumentException e) { + e.printStackTrace(); + } + + String className=""; + Element curActNode = null; + for(int i=0;i attrs = actions.get(i).attributes(); + for(int j=0;j class1 = null; + try { + class1 = Class.forName(className); + class1Instance = class1.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + for(String key : parameters.keySet()){ + String methodName = "set"+(new StringBuilder()).append(Character.toUpperCase(key.charAt(0))).append(key.substring(1)).toString(); + Object methodPara=parameters.get(key); + try { + Method method =class1.getMethod(methodName, String.class); + method.invoke(class1Instance, methodPara); + } catch (Exception e) { + e.printStackTrace(); + } + } + Object exeResult = null; + try { + Method method =class1.getMethod("execute"); + exeResult = method.invoke(class1Instance); + } catch (Exception e) { + e.printStackTrace(); + } + + String jsp = null; + List results = curActNode.elements(); + for(int i=0;i attrs = results.get(i).attributes(); + for(int j=0;j para = new HashMap(); + view.setParameters(para); + + Field [] fields = class1.getDeclaredFields(); + for(int i=0;i params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //ԤIJһ + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } + +} diff --git a/group12/247565311/week2/View.java b/group12/247565311/week2/View.java new file mode 100644 index 0000000000..4f88ad3b84 --- /dev/null +++ b/group12/247565311/week2/View.java @@ -0,0 +1,24 @@ +package week2; +import java.util.Map; +public class View { + private String jsp; + @SuppressWarnings("rawtypes") + private Map parameters; + + public String getJsp(){ + return jsp; + } + public View setJsp(String jsp){ + this.jsp = jsp; + return this; + } + @SuppressWarnings("rawtypes") + public Map getParameters(){ + return parameters; + } + @SuppressWarnings("rawtypes") + public View setParameters(Map parameters){ + this.parameters = parameters; + return this; + } +} diff --git a/group12/247565311/week2/struts.xml b/group12/247565311/week2/struts.xml new file mode 100644 index 0000000000..234232d0b6 --- /dev/null +++ b/group12/247565311/week2/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group12/247565311/week3/DownloadThread.java b/group12/247565311/week3/DownloadThread.java new file mode 100644 index 0000000000..3271ba2e99 --- /dev/null +++ b/group12/247565311/week3/DownloadThread.java @@ -0,0 +1,53 @@ +package week3; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; + +import week3.api.Connection; + +public class DownloadThread extends Thread{ + Connection conn; + int startPos; + int endPos; + String path = ""; + public DownloadThread( Connection conn, int startPos, int endPos,String filepath){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.path = filepath; + } + public void run(){ + // ȡصֽ飬дļעһ̳߳ + // ֻдһֵļ + + // connectȡֽ飬ûֽˣͱʾⲿ + // filepathдļ + if(conn == null) return; + ByteBuffer buffer = ByteBuffer.allocate(endPos-startPos); + Path filepath = Paths.get(path); + + if(filepath == null) return; + int curEndPos = startPos; + // while(curEndPos endPos) + curEndPos = endPos; + try { + byte[] data = conn.read(startPos, curEndPos); + FileChannel channel = FileChannel.open(filepath,StandardOpenOption.WRITE); + // System.out.println("startPos"+startPos + ", length:"+data.length); + buffer.put(data); + channel.write(buffer); + } catch (IOException e) { + //e.printStackTrace(); + System.out.println("дļ"); + } + // } + conn.close(); + } +} diff --git a/group12/247565311/week3/FileDownloader.java b/group12/247565311/week3/FileDownloader.java new file mode 100644 index 0000000000..c5ab5fb5d0 --- /dev/null +++ b/group12/247565311/week3/FileDownloader.java @@ -0,0 +1,74 @@ +package week3; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; + +import week3.api.Connection; +import week3.api.ConnectionException; +import week3.api.ConnectionManager; +import week3.api.DownloadListener; +import week3.impl.ConnectionManagerImpl; + +public class FileDownloader { + private String url = null,path=null; + DownloadListener listener = null; + private ConnectionManager cm = new ConnectionManagerImpl(); + + public FileDownloader(String weburl,String localpath) { + this.url = weburl; + this.path = localpath; + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + conn = cm.open(this.url); + int length = conn.getContentLength(); + // 在这里创建出一个同样大小的空文件, 路径是path + RandomAccessFile tarfile = new RandomAccessFile(path,"rw"); + tarfile.setLength(length); + tarfile.close(); + Thread[] threads = new Thread[4]; + threads[0] = new DownloadThread(cm.open(this.url),0,length/4,path); + threads[1] = new DownloadThread(cm.open(this.url),length/4,length/2,path); + threads[2] = new DownloadThread(cm.open(this.url),length/2,3*length/4,path); + threads[3] = new DownloadThread(cm.open(this.url),3*length/4,length,path); + for(int i=0;i<4;i++) + threads[i].start(); + threads[0].join(); + threads[1].join(); + threads[2].join(); + threads[3].join(); + this.getListener().notifyFinished(); + } catch (ConnectionException | IOException | InterruptedException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + } + public void setListener(DownloadListener listener) { + this.listener = listener; + } + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + public DownloadListener getListener(){ + return this.listener; + } +} diff --git a/group12/247565311/week3/FileDownloaderTest.java b/group12/247565311/week3/FileDownloaderTest.java new file mode 100644 index 0000000000..96893b71e9 --- /dev/null +++ b/group12/247565311/week3/FileDownloaderTest.java @@ -0,0 +1,45 @@ +package week3; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import week3.api.ConnectionManager; +import week3.api.DownloadListener; +import week3.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + String url = "https://edmullen.net/test/rc.jpg"; + String path = "D:\\hellp.jpg"; + FileDownloader downloader = new FileDownloader(url,path); + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + }); + downloader.execute(); + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + Thread.sleep(5000);//休眠5秒 + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + } +} diff --git a/group12/247565311/week3/LinkedList.java b/group12/247565311/week3/LinkedList.java new file mode 100644 index 0000000000..dbf9465386 --- /dev/null +++ b/group12/247565311/week3/LinkedList.java @@ -0,0 +1,252 @@ +package week3; + + +import java.util.NoSuchElementException; + +import week1.Iterator; +import week1.List; + +public class LinkedList implements List { + private Node head = new Node(); + private int size = 0; + private void checkAddIndex(int index){ + if(index > size || index<0) throw new IndexOutOfBoundsException("Index:"+index+", Size:"+size); + } + private void checkGetIndex(int index){ + if(index >= size || index<0) throw new IndexOutOfBoundsException("Index:"+index+", Size:"+size); + } + public void add(Object o){ + Node newNode = new Node(o),p = head; + while(p.next!=null) + p = p.next; + p.next = newNode; + size += 1; + } + /** + * + * */ + public void add(int index , Object o){ + checkAddIndex(index); + Node p = head; + for(int i=0;i7->10 , úΪ 10->7->3 + */ + public void reverse(){ + Node rhead = new Node(),p=head; + for(int i=0;i5->7->8 , ɾԺֵΪ 7->8 + * list = 2->5->7->8->10 ,ɾԺֵΪ7,8,10 + + */ + public void removeFirstHalf(){ + int numToRemove = size/2; + for(int i=0;i101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * صĽӦ[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + int []res = new int[list.size()]; + Node p = head.next,q = list.head.next; + int lenl = list.size(),index=0; + for(int i=0;imax) return; // Ŀ (min,max) + Node p = head; + while(p.next != null && ((Integer)p.next.data).intValue()<=min) // ɵԪ + p = p.next; + while(p.next != null && ((Integer)p.next.data).intValue()=endPos) return null; + byte[]res = null; + conn.setRequestProperty("Range","bytes="+startPos+"-"+endPos); + int responcode = conn.getResponseCode(); + if(200 < responcode && responcode < 300){ + InputStream input = conn.getInputStream(); + res = new byte[endPos-startPos]; + input.read(res); + input.close(); + } + conn.disconnect(); + return res; + } + + @Override + public int getContentLength() { + if(conn == null) return 0; + return conn.getContentLength(); + } + + @Override + public void close() { + if(conn == null) return; + conn.disconnect(); + } + public void setConn(HttpURLConnection urlconn) { + conn = urlconn; + } +} diff --git a/group12/247565311/week3/impl/ConnectionManagerImpl.java b/group12/247565311/week3/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..68e458b1ca --- /dev/null +++ b/group12/247565311/week3/impl/ConnectionManagerImpl.java @@ -0,0 +1,28 @@ +package week3.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +import week3.api.Connection; +import week3.api.ConnectionException; +import week3.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + URL urllink = null; + ConnectionImpl conImpl = null; + @Override + public Connection open(String url) throws ConnectionException { + try { + URL urllink = new URL(url); + conImpl = new ConnectionImpl(); + HttpURLConnection httpconn = (HttpURLConnection)urllink.openConnection(); + httpconn.setConnectTimeout(5*1000); + httpconn.setRequestProperty("User-Agent","Mozilla/4.0 (compatiable; MSIE 5.0; Windows NT; DigExt)"); // ģ + conImpl.setConn(httpconn); + } catch (Exception e) { + throw (ConnectionException)e; + } + return conImpl; + } +} diff --git a/group12/2686360536/ArrayList.java b/group12/2686360536/ArrayList.java new file mode 100644 index 0000000000..cf7eb423b0 --- /dev/null +++ b/group12/2686360536/ArrayList.java @@ -0,0 +1,34 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] data = new Object[100]; + + public void add(Object object) { + data[size] = object; + size++; + } + + public void add(int index, Object object) { + + } + + public Object get(int index) { + return data[index]; + } + + public Object remove(int index) { + return null; + } + + public int size() { + return size; + } + + public Iterator iterator() { + return null; + } + +} diff --git a/group12/2686360536/LinkedList.java b/group12/2686360536/LinkedList.java new file mode 100644 index 0000000000..6a8d0b237f --- /dev/null +++ b/group12/2686360536/LinkedList.java @@ -0,0 +1,80 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public class LinkedList implements List { + + private Node start; + private Node end; + private int size; + + public void add(Object object) { + if (start == null) { + start = new Node(object); + end = start; + } else { + Node node = new Node(object); + start.setNext(node); + end = node; + } + size++; + } + + public void add(int index, Object object) { + } + + + public Object get(int index) { + if(index > size -1) + return null; + + Node current = start; + for (int i = 0; i < index; i++) { + current = current.getNext(); + } + return current.getData(); + } + + public Object remove(int index) { + return null; + } + + public int size() { + return size; + } + + public void addFirst(Object object) { + Node node = new Node(object, start); + start = node; + } + + public void addEnd(Object object) { + Node node = new Node(object); + end.setNext(node); + end = node; + } + + public Object removeFirst() { + Object data = start.getData(); + start = start.getNext(); + return data; + + } + + public Object removeEnd() { + Object data = end.getData(); + Node current = start; + while(true){ + if (current.getNext() == end){ + end = current; + current.setNext(null); + break; + }else { + current = current.getNext(); + } + } + return data; + } + + public Iterator iterator() { + return null; + } +} diff --git a/group12/2686360536/List.java b/group12/2686360536/List.java new file mode 100644 index 0000000000..7822b0e26c --- /dev/null +++ b/group12/2686360536/List.java @@ -0,0 +1,9 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group12/2686360536/Node.java b/group12/2686360536/Node.java new file mode 100644 index 0000000000..999e3ee828 --- /dev/null +++ b/group12/2686360536/Node.java @@ -0,0 +1,43 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public class Node { + private Object data; + private Node next; + private Node previous; + + public Node() { + } + + public Node(Object data){ + this.data = data; + } + + public Node(Object data, Node next) { + this.data = data; + this.next = next; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Node getNext() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + public Node getPrevious() { + return previous; + } + + public void setPrevious(Node previous) { + this.previous = previous; + } +} \ No newline at end of file diff --git a/group12/2686360536/Queue.java b/group12/2686360536/Queue.java new file mode 100644 index 0000000000..10adea7fc4 --- /dev/null +++ b/group12/2686360536/Queue.java @@ -0,0 +1,28 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public class Queue { + private ArrayList elements = new ArrayList(); + + public void enQueue(Object object) { + elements.add(object); + } + + public Object deQueue() { + if (isEmpty()) + return null; + else { + return elements.remove(elements.size() - 1); + } + } + + public boolean isEmpty() { + if (elements.size() == 0) + return true; + else + return false; + } + + public int size() { + return elements.size(); + } +} diff --git a/group12/2686360536/Stack.java b/group12/2686360536/Stack.java new file mode 100644 index 0000000000..e2908b0fa5 --- /dev/null +++ b/group12/2686360536/Stack.java @@ -0,0 +1,38 @@ +package org.dul.CodingTask.homework_2017_2_25; + +public class Stack { + private ArrayList elements = new ArrayList(); + + public void push(Object object) { + elements.add(object); + } + + public Object pop() { + if (isEmpty()) + return null; + else { + return elements.remove(elements.size() - 1); + } + + } + + public Object peek() { + if (isEmpty()) + return null; + else { + return elements.get(elements.size() - 1); + } + } + + public boolean isEmpty() { + if (elements.size() == 0) + return true; + else + return false; + } + + public int size() { + return elements.size(); + } + +} diff --git a/group12/282742732/learning_1/.settings/org.eclipse.jdt.core.prefs b/group12/282742732/learning_1/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..3a21537071 --- /dev/null +++ b/group12/282742732/learning_1/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/group12/282742732/learning_1/src/com/coderising/array/ArrayUtil.java b/group12/282742732/learning_1/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..4d93afd1fd --- /dev/null +++ b/group12/282742732/learning_1/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,360 @@ +package com.coderising.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + * @return + */ + public int[] reverseArray(int[] origin){ + int[] newOrigin = new int[origin.length]; + + for (int i = 0; i < newOrigin.length; i++) { + newOrigin[i] = origin[origin.length-1-i]; + } + return newOrigin; + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + + int count = 0; + + + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] == 0) { + count++; + } + } + int newArray[] = new int[oldArray.length-count]; + int index = 0; + + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + newArray[index] = oldArray[i]; + index++; + } + } + + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + + int length = array1.length + array2.length; + + int TEMP[]= new int[length]; + System.arraycopy(array1, 0, TEMP, 0, array1.length); + System.arraycopy(array2, 0, TEMP, array1.length, array2.length); + + + for (int i = 0; i < array1.length; i++) { + for (int j = 0; j < array2.length; j++) { + if (array1[i]==array2[j]) { + length--; + } + } + } + + + + for (int i = 0; i < TEMP.length; i++) { + System.out.println(TEMP[i]); + } + + + int head = 0; + for (int i = 0; i < TEMP.length -1;i++) { + for (int j = i+1; j < TEMP.length; j++) { + if(TEMP[i]>TEMP[j]){ + int tempE=TEMP[i]; + TEMP[i] = TEMP[j]; + TEMP[j] = tempE; + } + } + } + + int NewArray[] = new int[length]; + int num = 0; + for (int i = 0; i < TEMP.length;i++) { + if (i parameters) { + + View view = new View(); + /* + + 0. 读取配置文件struts.xml + + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + + //Dom4J读取struts.xml + + //System.out.println(Struts.class.getResource("").getPath()); + + File file = new File(Struts.class.getResource("").getPath()+"struts.xml"); + + + SAXReader rd = new SAXReader(); + try { + Document doc = rd.read(file); + + Element root = doc.getRootElement(); + + Element action; + + for (Iterator iterator = root.elementIterator("action"); iterator.hasNext();) { + action = (Element) iterator.next(); + //System.out.println(action.attributeValue("name")+"===="+action.attributeValue("class")); + + + + if (null != actionName && actionName.equals(action.attributeValue("name")) ) { + + + //System.out.println(action.attributeValue("name")+"========"+action.attributeValue("class")); + + Class actionclass = Class.forName(action.attributeValue("class")); + + Object actionObj = actionclass.newInstance(); + + + Method[] methods = actionclass.getMethods(); + + for (int i = 0; i < methods.length; i++) { + + String methodName = methods[i].getName(); + + if (methodName.startsWith("set")) { + + if (parameters.get(methodName.substring(3).toLowerCase()) != null) { + + methods[i].invoke(actionObj, parameters.get(methodName.substring(3).toLowerCase())); + + } + + } + } + + Method meththod = actionclass.getMethod("execute", null); + + + + String result = (String) meththod.invoke(actionObj); + + Map resultParameters = new HashMap(); + + for (int i = 0; i < methods.length; i++) { + + String methodName = methods[i].getName(); + + if (methodName.startsWith("get")) { + + resultParameters.put(methodName.substring(3).toLowerCase(), methods[i].invoke(actionObj)); + + } + } + + + + Element resultElement; + for (Iterator iterator2 = action.elementIterator(); iterator2.hasNext();) { + resultElement = (Element) iterator2.next(); + if (resultElement.attributeValue("name").equals(result)) { + view.setJsp(resultElement.getText()); + view.setParameters(resultParameters); + } + + } + + } + + } + + + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return view; + } + + public static void main(String[] args) { + + Map map = new HashMap(); + + map.put("name","test"); + map.put("password","1234"); + + View view = runAction("login", map); + System.out.println(view.getJsp()); + + } +} diff --git a/group12/282742732/learning_1/src/com/coderising/litestruts/StrutsTest.java b/group12/282742732/learning_1/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..a44c1878ac --- /dev/null +++ b/group12/282742732/learning_1/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group12/282742732/learning_1/src/com/coderising/litestruts/View.java b/group12/282742732/learning_1/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..0194c681f6 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml b/group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..a4ca47c733 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/282742732/learning_1/src/com/coding/basic/ArrayList.java b/group12/282742732/learning_1/src/com/coding/basic/ArrayList.java new file mode 100644 index 0000000000..ec3f7399e7 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/ArrayList.java @@ -0,0 +1,124 @@ +package com.coding.basic; + + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + if (size+1>=elementData.length) { + this.groupLength(); + }else if (size==0){ + elementData[0]=o; + }else{ + elementData[size] = o; + } + size = size + 1; + } + public void add(int index, Object o){ + if (size+1>=elementData.length) { + this.groupLength(); + }else if (index == size ) { + elementData[size] = o; + }else if(index>=0 && index<=size ){ + Object[] elementDataNew = new Object[this.elementData.length]; + + System.arraycopy(elementData, 0, elementDataNew, 0, index); + elementDataNew[index]=o; + System.arraycopy(elementData, index, elementDataNew, index+1, size-index); + + this.elementData = elementDataNew; + }else{ + System.out.println("ָԽ"); + return; + } + + size = size + 1; + } + + public Object get(int index){ + + if (index>=0||index<=size) { + return elementData[index]; + }else{ + System.out.println("ָԽ"); + return null; + } + + } + + public Object remove(int index){ + + Object obj =this.elementData[index]; + Object[] elementDataNew = new Object[this.elementData.length]; + if (index<0 || index > size-1) { + System.out.println("ָԽ"); + return null; + }else if(index==0){ + System.arraycopy(elementData, 1, elementDataNew, 0, size-1); + }else if(index==size){ + System.arraycopy(elementData, 0, elementDataNew, 0, size-1); + }else if(index>0 && index <=size){ + System.arraycopy(elementData, 0, elementDataNew, 0, index); + System.arraycopy(elementData, index+1, elementDataNew, index, size-index-1); + } + + this.elementData = elementDataNew; + size=size-1; + return obj; + } + + public int size(){ + return size; + } + + public Iterator iterator(){ + + return new IteratorArrayList(elementData,size); + } + + private void groupLength(){ + this.elementData = new Object[this.elementData.length + 10]; + size=size+10; + } + + public static void main(String[] args) { + + + + ArrayList list = new ArrayList(); + System.out.println(list.size()); + + list.add("aaa"); +// System.out.println(list.remove(1)); + + list.add("bbb"); + + + list.add(1, "ccc"); + list.add(2, "ddd"); + +// System.out.println(list.size()); +// +// System.out.println( list.remove(0) ); +// +// list.add(0,"111"); +// list.add("xxxx"); + + System.out.println(list.size()); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)+","); + } + Iterator it = list.iterator(); + + int idex=0; + while (it.hasNext()) { + String str = (String) it.next(); + idex++; + System.out.println("str"+idex+"=="+str+";"); + + } + } +} diff --git a/group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java b/group12/282742732/learning_1/src/com/coding/basic/BinaryTreeNode.java similarity index 95% rename from group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java rename to group12/282742732/learning_1/src/com/coding/basic/BinaryTreeNode.java index 683868be1d..d7ac820192 100644 --- a/group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java +++ b/group12/282742732/learning_1/src/com/coding/basic/BinaryTreeNode.java @@ -1,4 +1,4 @@ -package com.hans; +package com.coding.basic; public class BinaryTreeNode { diff --git a/group10/904627477/src/com/coding/Iterator.java b/group12/282742732/learning_1/src/com/coding/basic/Iterator.java similarity index 75% rename from group10/904627477/src/com/coding/Iterator.java rename to group12/282742732/learning_1/src/com/coding/basic/Iterator.java index d2c1b79572..06ef6311b2 100644 --- a/group10/904627477/src/com/coding/Iterator.java +++ b/group12/282742732/learning_1/src/com/coding/basic/Iterator.java @@ -1,7 +1,7 @@ -package com.coding; - -public interface Iterator { - public boolean hasNext(); - public Object next(); - -} +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group12/282742732/learning_1/src/com/coding/basic/IteratorArrayList.java b/group12/282742732/learning_1/src/com/coding/basic/IteratorArrayList.java new file mode 100644 index 0000000000..faefc0de06 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/IteratorArrayList.java @@ -0,0 +1,40 @@ +package com.coding.basic; + +public class IteratorArrayList implements Iterator { + + + private Object[] elementData; + private int length; + + private int index = 0; + + public IteratorArrayList(Object[] elementData,int length){ + this.elementData = elementData; + this.length = length; + } + + @Override + public boolean hasNext() { + + if ((index+1)<=length) { + return true; + } + + return false; + } + + @Override + public Object next() { + if ((index+1)<=length) { + index = index + 1; + return elementData[index-1]; + }else{ + System.out.println("ָ볬Χ"); + return null; + } + + } + + + +} diff --git a/group12/282742732/learning_1/src/com/coding/basic/IteratorLinkedList.java b/group12/282742732/learning_1/src/com/coding/basic/IteratorLinkedList.java new file mode 100644 index 0000000000..558b90f05a --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/IteratorLinkedList.java @@ -0,0 +1,30 @@ +package com.coding.basic; + +import com.coding.basic.LinkedList.Node; + +public class IteratorLinkedList implements Iterator{ + + Node node ; + public IteratorLinkedList(Node node){ + this.node = node; + } + + @Override + public boolean hasNext() { + + if (node == null) { + return false; + } + return true; + + } + + @Override + public Object next() { + Object obj = this.node.data; + node = node.next; + return obj; + } + + +} diff --git a/group12/282742732/learning_1/src/com/coding/basic/LinkedList.java b/group12/282742732/learning_1/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..c5a28a35f8 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/LinkedList.java @@ -0,0 +1,239 @@ +package com.coding.basic; + + +public class LinkedList implements List { + + private Node head; + private Node last; + private int size = 0; + + public void add(Object o){ + if (head==null) { + head=new Node(o); + last=head; + }else{ + Node node = new Node(o); + last.setNext(node); + last = node; + } + size = size + 1; + } + public void add(int index , Object o){ + + if (index >=0 && index<=this.size && size>0) { + + if (index == 0) { + this.addFirst(o); + }else if(index == size){ + this.addLast(o); + }else{ + int num = 0; + Node node = head; + Node node1 = null; + Node nodenew = new Node(o); + Node node3 = null; + while (num <= index){ + + if(index - 1 == num){ + node1 = node; + }else if(index == num){ + node3 = node; + } + node = node.next; + num = num +1; + }; + nodenew.setNext(node3); + node1.setNext(nodenew); + + + size = size + 1; + } + + }else{ + System.out.println("ָԽ"); + } + + } + public Object get(int index){ + + + if (index >=0 && index<=this.size && size>0) { + int num = 0; + Node node = head; + while (num < size){ + if(index == num){ + return node.getData(); + }else{ + node = node.next; + num = num +1; + } + }; + }else{ + System.out.println("ָԽ"); + return null; + } + return null; + } + public Object remove(int index){ + + if (index >=0 && index<=this.size && size>0) { + + if (index == 0) { + return this.removeFirst(); + }else if(index+1==size){ + return this.removeLast(); + }else{ + int num = 0; + Node node = head; + Node node1 = null; + Node node2 = null; + Node node3 = null; + while (num <= index+1){ + if(index - 1 == num){ + node1 = node; + }else if(index+1 == num){ + node3 = node; + }else if(index == num){ + node2 = node; + } + node = node.next; + num = num +1; + }; + node1.setNext(node3); + size = size - 1; + return node2.data; + } + + }else{ + System.out.println("ָԽ"); + return null; + } + + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + Node node = new Node(o); + node.setNext(head); + head = node; + size = size + 1; + } + public void addLast(Object o){ + Node node = new Node(o); + last.setNext(node); + last = node; + size = size + 1; + } + public Object removeFirst(){ + Object obj = null; + if(size > 0){ + obj = head.data; + head = head.next; + }else{ + System.out.println("ָԽ"); + return null; + } + + size = size - 1; + return obj; + } + public Object removeLast(){ + Object obj = null; + if(this.size() > 0){ + if(this.size()==1){ + obj = head.data; + this.head = null; + }else if (this.size()==2) { + obj = head.next.data; + this.head.setNext(null); + }else{ + int num = 0; + Node node = head; + Node node1 = null; + Node node2 = null; + Node node3 = null; + while (num <= size-2){ + if(size - 2 == num){ + obj = node.next.data; + node.setNext(null); + last = node; + }else{ + node = node.next; + } + + num = num +1; + }; + } + }else{ + System.out.println("ָԽ"); + return null; + } + + + + size = size - 1; + return obj; + } + public Iterator iterator(){ + return new IteratorLinkedList(this.head); + } + + + static class Node{ + Object data; + Node next; + + public Node(Object object) { + data = object; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Node getNext() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + } + + + public static void main(String[] args) { + LinkedList list = new LinkedList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); +// System.out.println(list.removeLast()); +// System.out.println(list.removeFirst()); +// list.add(3,"xxxxxx"); +// System.out.println("======="+list.removeFirst()); +// System.out.println(list.size()); +// +// System.out.println("list.get0========"+list.get(0)); +// System.out.println("list.get1========"+list.get(1)); +// System.out.println("============="); + System.out.println(list.size()); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + + Iterator it = list.iterator(); + + while(it.hasNext()){ + String str = (String) it.next(); + System.out.println("str====="+str); + } + + } +} diff --git a/group10/904627477/src/com/coding/List.java b/group12/282742732/learning_1/src/com/coding/basic/List.java similarity index 86% rename from group10/904627477/src/com/coding/List.java rename to group12/282742732/learning_1/src/com/coding/basic/List.java index 5e78eced11..10d13b5832 100644 --- a/group10/904627477/src/com/coding/List.java +++ b/group12/282742732/learning_1/src/com/coding/basic/List.java @@ -1,9 +1,9 @@ -package com.coding; - -public interface List { - public void add(Object o); - public void add(int index, Object o); - public Object get(int index); - public Object remove(int index); - public int size(); -} +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group12/282742732/learning_1/src/com/coding/basic/Queue.java b/group12/282742732/learning_1/src/com/coding/basic/Queue.java new file mode 100644 index 0000000000..d16a441644 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/Queue.java @@ -0,0 +1,22 @@ +package com.coding.basic; + +public class Queue { + + LinkedList elementData = new LinkedList(); + public void enQueue(Object o){ + elementData.add(o); + } + + public Object deQueue(){ + + return null; + } + + public boolean isEmpty(){ + return false; + } + + public int size(){ + return -1; + } +} diff --git a/group12/282742732/learning_1/src/com/coding/basic/Stack.java b/group12/282742732/learning_1/src/com/coding/basic/Stack.java new file mode 100644 index 0000000000..31b24fd136 --- /dev/null +++ b/group12/282742732/learning_1/src/com/coding/basic/Stack.java @@ -0,0 +1,42 @@ +package com.coding.basic; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + return elementData.remove(elementData.size()-1); + } + + public Object peek(){ + return elementData.get(elementData.size()-1); + } + public boolean isEmpty(){ + if (elementData.size()>0) { + return false; + } + return true; + } + public int size(){ + return elementData.size(); + } + + public static void main(String[] args) { + + Stack st = new Stack(); + st.push("aaa"); + st.push("bbb"); + st.push("ccc"); + System.out.println(st.isEmpty()); + int length = st.size(); + + for (int i = 0; i < length; i++) { + System.out.println(st.peek()); + } + + System.out.println(st.isEmpty()); + } +} diff --git a/group12/282742732/learning_1/src/lib/dom4j-1.6.1.jar b/group12/282742732/learning_1/src/lib/dom4j-1.6.1.jar new file mode 100644 index 0000000000..c8c4dbb92d Binary files /dev/null and b/group12/282742732/learning_1/src/lib/dom4j-1.6.1.jar differ diff --git a/group12/377401843/learning_1/.gitignore b/group12/377401843/learning/.gitignore similarity index 51% rename from group12/377401843/learning_1/.gitignore rename to group12/377401843/learning/.gitignore index b12088665a..8bd3a05882 100644 --- a/group12/377401843/learning_1/.gitignore +++ b/group12/377401843/learning/.gitignore @@ -1,3 +1,4 @@ -/bin/ -/.project +/target/ +/.settings/ /.classpath +/.project diff --git a/group12/377401843/learning/pom.xml b/group12/377401843/learning/pom.xml new file mode 100644 index 0000000000..f252611284 --- /dev/null +++ b/group12/377401843/learning/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + com.zhaogd.projects + learning + 1.0.0 + jar + + + + junit + junit + 4.12 + + + + dom4j + dom4j + 1.6.1 + + + + + + + + ${project.basedir}/src/main/resources + true + + + ${project.basedir}/src/main/java + + **/*.java + + + + + + + ${project.basedir}/src/test/java + + **/*.java + + + + ${project.basedir}/src/test/resources + + + ${project.basedir}/src/main/java + + **/*.java + + + + ${project.basedir}/src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + 1.8 + UTF-8 + true + 128m + 512m + + + + + diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/array/ArrayUtil.java b/group12/377401843/learning/src/main/java/com/zhaogd/array/ArrayUtil.java new file mode 100644 index 0000000000..64596aa807 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/array/ArrayUtil.java @@ -0,0 +1,173 @@ +package com.zhaogd.array; + +import java.util.Arrays; +import java.util.HashSet; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] 如果 a = + * [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + for (int i = 0; i < origin.length / 2; i++) { + int tmp = origin[i]; + origin[i] = origin[origin.length - 1 - i]; + origin[origin.length - 1 - i] = tmp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + public int[] removeZero(int[] oldArray) { + int[] newArr = new int[oldArray.length]; + int z = 0; + for (int i : oldArray) { + if (i != 0) { + newArr[z] = i; + z++; + } + } + return Arrays.copyOf(newArr, z); + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 例如 a1 = + * [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + public int[] merge(int[] array1, int[] array2) { + HashSet set = new HashSet<>(); + for (Integer i : array1) { + set.add(i); + } + for (Integer i : array2) { + set.add(i); + } + int[] array3 = new int[set.size()]; + int i = 0; + for (int s : set) { + array3[i] = s; + i++; + } + Arrays.sort(array3); + + return array3; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + return Arrays.copyOf(oldArray, oldArray.length + size); + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 例如, max = 15 , + * 则返回的数组应该为 [1,1,2,3,5,8,13] max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + if (max == 1) { + return new int[] {}; + } + int a = 1; + int b = 1; + int count = 2; + for (int i = 1; i < max; i = a + b) { + a = b; + b = i; + count++; + } + int[] array = new int[count-1]; + array[0] = array[1] = 1; + for (int i = 2; i < array.length; i++) { + array[i] = array[i - 2] + array[i - 1]; + } + return array; + } + + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + int[] array = new int[max]; + int z = 0; + for (int i = 2; i < max; i++) { + boolean flag = true; + for (int j = 2; j <= Math.sqrt(i); j++) { + if (i % j == 0) { //如果取模为0,则为合数 + flag = false; + break; + } + } + if (flag) { + array[z] = i; + z++; + } + } + return Arrays.copyOf(array, z); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int[] array = new int[max]; + int z = 0; + for (int i = 0; i < max; i++) { + int tmp = 0; + for (int j = 1; j < i / 2 + 1; j++) { + if (i % j == 0) { + tmp += j; + } + } + if (tmp == i) { + array[z] = tmp; + z++; + } + } + + return Arrays.copyOf(array, z); + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) { + String s = ""; + for (int i = 0; i < array.length; i++) { + s += array[i] + seperator; + } + return s.substring(0, s.length() - 1); + } +} diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/ArrayList.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/ArrayList.java similarity index 91% rename from group12/377401843/learning_1/src/com/guodong/datastructure/ArrayList.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/ArrayList.java index 880af45da8..d3afc5e01a 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/ArrayList.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/ArrayList.java @@ -1,4 +1,4 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; import java.util.Arrays; @@ -7,7 +7,7 @@ public class ArrayList implements List { private int size = 0; private Object[] elementData = new Object[100]; - + /** * 按下标顺序新增元素 * @@ -31,17 +31,17 @@ public void add(Object o) { */ public void add(int index, Object o) { checkRangeForAdd(index); - + ensureCapacityInternal(size + 1); - + System.arraycopy(elementData, index, elementData, index + 1, size - index); - + elementData[index] = o; size++; } /** - * 根据下标获取列表数据 + * 根据下标获取列表数据 * * @Method get * @param index @@ -50,7 +50,7 @@ public void add(int index, Object o) { */ public Object get(int index) { checkRangeForGetOrRemove(index); - + return elementData[index]; } @@ -64,14 +64,14 @@ public Object get(int index) { */ public Object remove(int index) { checkRangeForGetOrRemove(index); - + Object oldValue = elementData[index]; - - System.arraycopy(elementData, index + 1, elementData, index, size - index -1); - + + System.arraycopy(elementData, index + 1, elementData, index, size - index - 1); + size--; elementData[size] = null; - + return oldValue; } @@ -107,7 +107,7 @@ public Iterator iterator() { * @param minCapacity */ private void ensureCapacityInternal(int minCapacity) { - if(minCapacity > elementData.length){ + if (minCapacity > elementData.length) { grow(minCapacity); } } @@ -124,7 +124,7 @@ private void grow(int minCapacity) { minCapacity = elementData.length + elementData.length / 2; elementData = Arrays.copyOf(elementData, minCapacity); } - + /** * 检查Add方法的下标范围是否合法 * @@ -134,11 +134,11 @@ private void grow(int minCapacity) { * @param index */ private void checkRangeForAdd(int index) { - if(index > size || index < 0){ + if (index > size || index < 0) { throw new IndexOutOfBoundsException("Index:" + index + ",Size:" + size); } } - + /** * 检查Get或者Remove方法的下标范围是否合法 * @@ -148,16 +148,15 @@ private void checkRangeForAdd(int index) { * @param index */ private void checkRangeForGetOrRemove(int index) { - if(index >= size || index < 0){ + if (index >= size || index < 0) { throw new IndexOutOfBoundsException("Index:" + index + ",Size:" + size); } } - - - private class ArrayListIterator implements Iterator{ + + private class ArrayListIterator implements Iterator { private int lastIndex = 0; - + @Override public boolean hasNext() { return lastIndex < size; diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/BinaryTreeNode.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/BinaryTreeNode.java similarity index 96% rename from group12/377401843/learning_1/src/com/guodong/datastructure/BinaryTreeNode.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/BinaryTreeNode.java index 2ced039d20..ee256391e7 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/BinaryTreeNode.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/BinaryTreeNode.java @@ -1,4 +1,4 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; public class BinaryTreeNode { diff --git a/group13/1274639949/lesson01/src/com/hans/Iterator.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java similarity index 66% rename from group13/1274639949/lesson01/src/com/hans/Iterator.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java index 4ec870ed01..0d9e6013d6 100644 --- a/group13/1274639949/lesson01/src/com/hans/Iterator.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java @@ -1,8 +1,9 @@ -package com.hans; +package com.zhaogd.collection; public interface Iterator { + public boolean hasNext(); + public Object next(); - public void remove(); -} +} diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/LinkedList.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/LinkedList.java similarity index 73% rename from group12/377401843/learning_1/src/com/guodong/datastructure/LinkedList.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/LinkedList.java index 976129cc84..136f53284e 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/LinkedList.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/LinkedList.java @@ -1,4 +1,4 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; import java.util.NoSuchElementException; @@ -175,6 +175,83 @@ public Object removeLast() { size--; return data; } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public static int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } + /** * 根据下标获取对应的节点 diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/List.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/List.java similarity index 83% rename from group12/377401843/learning_1/src/com/guodong/datastructure/List.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/List.java index 1a6f12da52..fb2f1bb78e 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/List.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/List.java @@ -1,7 +1,7 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; public interface List { - + public void add(Object o); public void add(int index, Object o); diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/Queue.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Queue.java similarity index 89% rename from group12/377401843/learning_1/src/com/guodong/datastructure/Queue.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/Queue.java index 6dc85d8ec0..d4a0647ab6 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/Queue.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Queue.java @@ -1,4 +1,4 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; public class Queue { private LinkedList element = new LinkedList(); diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/Stack.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Stack.java similarity index 91% rename from group12/377401843/learning_1/src/com/guodong/datastructure/Stack.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/Stack.java index c2b5049e73..afb01f5f92 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/Stack.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Stack.java @@ -1,4 +1,4 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; public class Stack { private LinkedList elementData = new LinkedList(); diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/DownloadThread.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/DownloadThread.java new file mode 100644 index 0000000000..769804eee2 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.zhaogd.download; + +import com.zhaogd.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloader.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloader.java new file mode 100644 index 0000000000..44601853b0 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.zhaogd.download; + +import com.zhaogd.download.api.Connection; +import com.zhaogd.download.api.ConnectionException; +import com.zhaogd.download.api.ConnectionManager; +import com.zhaogd.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloaderTest.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloaderTest.java new file mode 100644 index 0000000000..bf68184c2a --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.zhaogd.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.zhaogd.download.api.ConnectionManager; +import com.zhaogd.download.api.DownloadListener; +import com.zhaogd.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/api/Connection.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/Connection.java new file mode 100644 index 0000000000..f0154b8dc1 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.zhaogd.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionException.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionException.java new file mode 100644 index 0000000000..6977db3833 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionException.java @@ -0,0 +1,7 @@ +package com.zhaogd.download.api; + +public class ConnectionException extends Exception { + + private static final long serialVersionUID = -7548056370349716747L; + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionManager.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionManager.java new file mode 100644 index 0000000000..96bd21be2a --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.zhaogd.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/api/DownloadListener.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/DownloadListener.java new file mode 100644 index 0000000000..dfb5464ad2 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.zhaogd.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionImpl.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..b2951c3c9c --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.zhaogd.download.impl; + +import java.io.IOException; + +import com.zhaogd.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionManagerImpl.java b/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..32b7acacbf --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.zhaogd.download.impl; + +import com.zhaogd.download.api.Connection; +import com.zhaogd.download.api.ConnectionException; +import com.zhaogd.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/LoginAction.java b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/LoginAction.java new file mode 100644 index 0000000000..9011030c54 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/LoginAction.java @@ -0,0 +1,42 @@ +package com.zhaogd.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * + * @author liuxin + * + */ +public class LoginAction { + private String name; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute() { + if ("test".equals(name) && "1234".equals(password)) { + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name) { + this.name = name; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMessage() { + return this.message; + } +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/Struts.java b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/Struts.java new file mode 100644 index 0000000000..f9c8afc214 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/Struts.java @@ -0,0 +1,77 @@ +package com.zhaogd.litestruts; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +public class Struts { + + @SuppressWarnings("unchecked") + public static View runAction(String actionName, Map parameters) throws Exception { + + SAXReader reader = new SAXReader(); + Document document = reader.read(Struts.class.getResourceAsStream("/struts.xml")); + Element rootElement = document.getRootElement(); + List elements = rootElement.elements("action"); + + HashMap hashMap = new HashMap(); + for (Element element : elements) { + String name = element.attributeValue("name"); + if (name != null && !"".equals(name) && actionName.equals(name)) { + hashMap.put("actionName", name); + hashMap.put("class", element.attributeValue("class")); + List resultElements = element.elements("result"); + for (Element resultElement : resultElements) { + hashMap.put(resultElement.attributeValue("name"), (String) resultElement.getData()); + } + break; + } + } + + Class c = Class.forName(hashMap.get("class")); + Object o = c.newInstance(); + Set> entrySet = parameters.entrySet(); + for (Entry parameter : entrySet) { + Method method = o.getClass().getMethod("set" + parameter.getKey().substring(0, 1).toUpperCase() + + parameter.getKey().substring(1).toLowerCase(), String.class); + method.invoke(o, parameter.getValue()); + } + + Method exectue = o.getClass().getMethod("execute"); + String invoke = (String) exectue.invoke(o); + + View view = new View(); + view.setJsp(hashMap.get(invoke)); + HashMap p = new HashMap(); + p.put("message", (String) o.getClass().getMethod("getMessage").invoke(o)); + view.setParameters(p); + + /* + * + * 0. 读取配置文件struts.xml + * + * 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + * 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 ("name"="test" , + * "password"="1234") , 那就应该调用 setName和setPassword方法 + * + * 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + * + * 3. 通过反射找到对象的所有getter方法(例如 getMessage), 通过反射来调用, 把值和属性形成一个HashMap , 例如 + * {"message": "登录成功"} , 放到View对象的parameters + * + * 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + * 放到View对象的jsp字段中。 + * + */ + + return view; + } + +} diff --git a/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/StrutsTest.java b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/StrutsTest.java new file mode 100644 index 0000000000..1a213157f3 --- /dev/null +++ b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.zhaogd.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() throws Exception { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() throws Exception { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/View.java b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/View.java similarity index 92% rename from group20/592146505/coderising/src/org/wsc/litestruts/View.java rename to group12/377401843/learning/src/main/java/com/zhaogd/litestruts/View.java index f21906d1a5..f5a451e7fc 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/View.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/litestruts/View.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts; +package com.zhaogd.litestruts; import java.util.Map; diff --git a/group12/377401843/learning/src/main/resources/struts.xml b/group12/377401843/learning/src/main/resources/struts.xml new file mode 100644 index 0000000000..8e318d5de1 --- /dev/null +++ b/group12/377401843/learning/src/main/resources/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/377401843/learning/src/test/java/com/zhaogd/array/ArrayUtilTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/array/ArrayUtilTest.java new file mode 100644 index 0000000000..f08eab4b3e --- /dev/null +++ b/group12/377401843/learning/src/test/java/com/zhaogd/array/ArrayUtilTest.java @@ -0,0 +1,62 @@ +package com.zhaogd.array; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ArrayUtilTest { + private ArrayUtil arrayUtil = null; + + @Before + public void setUp() throws Exception { + arrayUtil = new ArrayUtil(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testReverseArray() { + int[] origin = new int[] { 7, 9, 30, 3 }; + arrayUtil.reverseArray(origin); + assertArrayEquals(origin, new int[] { 3, 30, 9, 7 }); + } + + @Test + public void testRemoveZero() { + int oldArr[] = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 }; + int[] newArr = arrayUtil.removeZero(oldArr); + assertArrayEquals(newArr, new int[] { 1, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5 }); + } + + @Test + public void testMerge() { + int arr1[] = { 3, 5, 7, 8 }; + int arr2[] = { 4, 5, 6, 7 }; + int[] arr3 = arrayUtil.merge(arr1, arr2); + + assertArrayEquals(arr3, new int[] { 3, 4, 5, 6, 7, 8 }); + } + + @Test + public void testGrow() { + int[] arr = { 2, 3, 6 }; + int[] newArr = arrayUtil.grow(arr, 3); + assertArrayEquals(newArr, new int[] { 2, 3, 6, 0, 0, 0 }); + } + + @Test + public void testFibonacci() { + assertArrayEquals(new int[] {}, arrayUtil.fibonacci(1)); + assertArrayEquals(new int[] { 1, 1, 2, 3, 5, 8, 13 }, arrayUtil.fibonacci(15)); + } + + @Test + public void testGetPrimes() { + assertArrayEquals(new int[] { 2, 3, 5, 7, 11, 13, 17, 19 }, arrayUtil.getPrimes(23)); + } + +} diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/test/ArrayListTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/collection/ArrayListTest.java similarity index 94% rename from group12/377401843/learning_1/src/com/guodong/datastructure/test/ArrayListTest.java rename to group12/377401843/learning/src/test/java/com/zhaogd/collection/ArrayListTest.java index f38f58614d..c54e99b4db 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/test/ArrayListTest.java +++ b/group12/377401843/learning/src/test/java/com/zhaogd/collection/ArrayListTest.java @@ -1,14 +1,13 @@ -package com.guodong.datastructure.test; +package com.zhaogd.collection; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.guodong.datastructure.ArrayList; -import com.guodong.datastructure.Iterator; - public class ArrayListTest { ArrayList arrayList; @@ -126,7 +125,7 @@ public void testSize() { public void testIterator() { Iterator iterator = arrayList.iterator(); assertFalse(iterator.hasNext()); - + arrayList.add(1); assertTrue(iterator.hasNext()); assertEquals(1, iterator.next()); diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/test/BinaryTreeNodeTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/collection/BinaryTreeNodeTest.java similarity index 85% rename from group12/377401843/learning_1/src/com/guodong/datastructure/test/BinaryTreeNodeTest.java rename to group12/377401843/learning/src/test/java/com/zhaogd/collection/BinaryTreeNodeTest.java index 537cd5961f..797d457c21 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/test/BinaryTreeNodeTest.java +++ b/group12/377401843/learning/src/test/java/com/zhaogd/collection/BinaryTreeNodeTest.java @@ -1,13 +1,11 @@ -package com.guodong.datastructure.test; +package com.zhaogd.collection; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.guodong.datastructure.BinaryTreeNode; - public class BinaryTreeNodeTest { private BinaryTreeNode binaryTreeNode; diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/test/LinkedListTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/collection/LinkedListTest.java similarity index 93% rename from group12/377401843/learning_1/src/com/guodong/datastructure/test/LinkedListTest.java rename to group12/377401843/learning/src/test/java/com/zhaogd/collection/LinkedListTest.java index 52d42b5aa7..32cac4bc6d 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/test/LinkedListTest.java +++ b/group12/377401843/learning/src/test/java/com/zhaogd/collection/LinkedListTest.java @@ -1,14 +1,13 @@ -package com.guodong.datastructure.test; +package com.zhaogd.collection; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.guodong.datastructure.Iterator; -import com.guodong.datastructure.LinkedList; - public class LinkedListTest { private LinkedList linkedList; @@ -44,8 +43,8 @@ public void testAddIntObject() { linkedList.add(0, 1); linkedList.add(1, 2); assertEquals(1, linkedList.get(0)); - - linkedList.add(1,3); + + linkedList.add(1, 3); assertEquals(2, linkedList.get(2)); assertEquals(3, linkedList.get(1)); assertEquals(3, linkedList.size()); @@ -55,17 +54,17 @@ public void testAddIntObject() { public void testExceptionForGet1() { linkedList.get(-1); } - + @Test(expected = IndexOutOfBoundsException.class) public void testExceptionForGet2() { linkedList.get(0); } - + @Test(expected = IndexOutOfBoundsException.class) public void testExceptionForGet3() { linkedList.get(1); } - + @Test public void testGet() { linkedList.add(0, 1); @@ -77,7 +76,7 @@ public void testGet() { public void testGetLast() { linkedList.add(1); assertEquals(1, linkedList.getLast()); - + linkedList.add(2); assertEquals(2, linkedList.getLast()); } @@ -101,7 +100,7 @@ public void testSize() { public void testAddFirst() { linkedList.addFirst(1); assertEquals(1, linkedList.get(0)); - + linkedList.addFirst(2); linkedList.addFirst(3); assertEquals(3, linkedList.get(0)); @@ -133,7 +132,7 @@ public void testRemoveLast() { public void testIterator() { Iterator iterator = linkedList.iterator(); assertFalse(iterator.hasNext()); - + linkedList.add(1); assertTrue(iterator.hasNext()); assertEquals(1, iterator.next()); diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/test/QueueTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/collection/QueueTest.java similarity index 84% rename from group12/377401843/learning_1/src/com/guodong/datastructure/test/QueueTest.java rename to group12/377401843/learning/src/test/java/com/zhaogd/collection/QueueTest.java index 1773b5027c..29c5e15752 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/test/QueueTest.java +++ b/group12/377401843/learning/src/test/java/com/zhaogd/collection/QueueTest.java @@ -1,6 +1,8 @@ -package com.guodong.datastructure.test; +package com.zhaogd.collection; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.NoSuchElementException; @@ -8,8 +10,6 @@ import org.junit.Before; import org.junit.Test; -import com.guodong.datastructure.Queue; - public class QueueTest { private Queue queue; diff --git a/group12/377401843/learning_1/src/com/guodong/datastructure/test/StackTest.java b/group12/377401843/learning/src/test/java/com/zhaogd/collection/StackTest.java similarity index 79% rename from group12/377401843/learning_1/src/com/guodong/datastructure/test/StackTest.java rename to group12/377401843/learning/src/test/java/com/zhaogd/collection/StackTest.java index 74ac8e7cc7..510e4c45f6 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/test/StackTest.java +++ b/group12/377401843/learning/src/test/java/com/zhaogd/collection/StackTest.java @@ -1,15 +1,15 @@ -package com.guodong.datastructure.test; +package com.zhaogd.collection; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.guodong.datastructure.Stack; - public class StackTest { - + private Stack stack; @Before diff --git a/group12/382266293/.classpath b/group12/382266293/.classpath index 3e0fb272a8..248236a6c0 100644 --- a/group12/382266293/.classpath +++ b/group12/382266293/.classpath @@ -1,7 +1,11 @@ - - - - - - - + + + + + + + + + + + diff --git a/group12/382266293/.gitignore b/group12/382266293/.gitignore index ae3c172604..88284eee9a 100644 --- a/group12/382266293/.gitignore +++ b/group12/382266293/.gitignore @@ -1 +1,2 @@ /bin/ +/*.lyj diff --git a/group12/382266293/src/Collection/AbstractList.java b/group12/382266293/coding/basic/collection/AbstractList.java similarity index 69% rename from group12/382266293/src/Collection/AbstractList.java rename to group12/382266293/coding/basic/collection/AbstractList.java index a81e76b587..80bdb5329f 100644 --- a/group12/382266293/src/Collection/AbstractList.java +++ b/group12/382266293/coding/basic/collection/AbstractList.java @@ -1,24 +1,25 @@ -package Collection; +package collection; public abstract class AbstractList implements List { protected static final String PREFIX = "["; protected static final String SUFFIX = "]"; protected static final String SEPERATOR = ", "; - protected static final int MAX_SIZE = Integer.MAX_VALUE/3; - + protected static final int MAX_SIZE = Integer.MAX_VALUE / 3; + protected void checkIndex(int i) { - if( i < 0 || i > Math.min(size(), MAX_SIZE)) - throw new IndexOutOfBoundsException("Size :" + size()+", Index: " + i); + if (i < 0 || i > Math.min(size(), MAX_SIZE)) + throw new IndexOutOfBoundsException("Size :" + size() + ", Index: " + i); } - + + @Override public boolean isEmpty() { return size() == 0; } - + @Override public int indexOf(E e) { - for (int i = 0; i < size()-1; i++) { + for (int i = 0; i < size() - 1; i++) { if (get(i).equals(e)) return i; } @@ -26,18 +27,18 @@ public int indexOf(E e) { } protected abstract Iterator iterator(); - + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(PREFIX); for (int i = 0; i < size(); i++) { sb.append(get(i)); - if (i < size()-1) + if (i < size() - 1) sb.append(SEPERATOR); } sb.append(SUFFIX); return sb.toString(); } - + } diff --git a/group12/382266293/src/Collection/Iterator.java b/group12/382266293/coding/basic/collection/Iterator.java similarity index 79% rename from group12/382266293/src/Collection/Iterator.java rename to group12/382266293/coding/basic/collection/Iterator.java index d51656a3a8..01d805b630 100644 --- a/group12/382266293/src/Collection/Iterator.java +++ b/group12/382266293/coding/basic/collection/Iterator.java @@ -1,7 +1,8 @@ -package Collection; +package collection; public interface Iterator { public boolean hasNext(); + public E next(); } diff --git a/group12/382266293/src/Collection/List.java b/group12/382266293/coding/basic/collection/List.java similarity index 82% rename from group12/382266293/src/Collection/List.java rename to group12/382266293/coding/basic/collection/List.java index 7ddb685cac..a1652bddd8 100644 --- a/group12/382266293/src/Collection/List.java +++ b/group12/382266293/coding/basic/collection/List.java @@ -1,16 +1,15 @@ -package Collection; +package collection; public interface List { - + public void add(E e); - + public int size(); - + public E get(int index); - + public boolean isEmpty(); - + public int indexOf(E e); - } diff --git a/group12/382266293/src/Collection/Concrete/ArrayList.java b/group12/382266293/coding/basic/collection/concrete/ArrayList.java similarity index 87% rename from group12/382266293/src/Collection/Concrete/ArrayList.java rename to group12/382266293/coding/basic/collection/concrete/ArrayList.java index 3db5ab47e6..3eeca56fee 100644 --- a/group12/382266293/src/Collection/Concrete/ArrayList.java +++ b/group12/382266293/coding/basic/collection/concrete/ArrayList.java @@ -1,10 +1,10 @@ -package Collection.Concrete; +package collection.concrete; import java.util.Arrays; import java.util.NoSuchElementException; -import Collection.AbstractList; -import Collection.Iterator; +import collection.AbstractList; +import collection.Iterator; public class ArrayList extends AbstractList { @@ -12,12 +12,11 @@ public class ArrayList extends AbstractList { private int size; private static final int INITIAL_SIZE = 16; - public ArrayList() { elements = (E[]) new Object[INITIAL_SIZE]; size = 0; } - + @Override public void add(E e) { checkCapacity(); @@ -27,21 +26,21 @@ public void add(E e) { private void checkCapacity() { if (size >= MAX_SIZE) throw new IndexOutOfBoundsException("Reached max size"); - + if (elements.length - size < INITIAL_SIZE) grow(); } synchronized private void grow() { - + int newCapacity = size * 2; newCapacity = (newCapacity < 0 || newCapacity - MAX_SIZE > 0) ? MAX_SIZE : newCapacity; E[] target = (E[]) new Object[newCapacity]; System.arraycopy(elements, 0, target, 0, size); elements = target; - + } - + public void add(int index, E e) { checkCapacity(); if (index == size) { @@ -50,46 +49,44 @@ public void add(int index, E e) { } checkIndex(index); synchronized (this) { - System.arraycopy(elements, index, elements, index+1, size-index+1); + System.arraycopy(elements, index, elements, index + 1, size - index + 1); elements[index] = e; size++; } } - + @Override public E get(int index) { checkIndex(index); - return elements[index]; + return elements[index]; } - public E getLast() { - return get(size-1); + return get(size - 1); } - + public void addLast(E e) { - add(e); + add(e); } - + public E removeLast() { return elements[--size]; } - + public E remove(int index) { checkIndex(index); E result = elements[index]; synchronized (this) { - System.arraycopy(elements, index+1, elements, index, size-index-1); + System.arraycopy(elements, index + 1, elements, index, size - index - 1); elements[--size] = null; } return result; } - + @Override public int size() { return size; } - @Override public int hashCode() { @@ -116,15 +113,16 @@ public boolean equals(Object obj) { return true; } - public Iterator iterator(){ + @Override + public Iterator iterator() { return new ArrayListIterator(this); } - + private class ArrayListIterator implements Iterator { private ArrayList myArrayList; private int pos; - + public ArrayListIterator(ArrayList arrayList) { myArrayList = arrayList; pos = 0; @@ -143,6 +141,4 @@ public E next() { } } - - } diff --git a/group12/382266293/src/Collection/Concrete/BinaryTreeNode.java b/group12/382266293/coding/basic/collection/concrete/BinaryTreeNode.java similarity index 50% rename from group12/382266293/src/Collection/Concrete/BinaryTreeNode.java rename to group12/382266293/coding/basic/collection/concrete/BinaryTreeNode.java index 34a9d4253e..3957711eb1 100644 --- a/group12/382266293/src/Collection/Concrete/BinaryTreeNode.java +++ b/group12/382266293/coding/basic/collection/concrete/BinaryTreeNode.java @@ -1,77 +1,73 @@ -package Collection.Concrete; +package collection.concrete; public class BinaryTreeNode> { - + private E data; private BinaryTreeNode left; private BinaryTreeNode right; private int size; private ArrayList myList; - - public BinaryTreeNode() { this.data = null; this.left = null; this.right = null; } - + public BinaryTreeNode(E data) { this.data = data; this.left = null; this.right = null; } - - public boolean isEmpty() { - return data == null; - } - - public int size() { - return size; - } - - public BinaryTreeNode insert(E o) { - BinaryTreeNode res; - if (isEmpty()) { - data = o; - size++; - return this; - } else { - BinaryTreeNode p = this; - res = new BinaryTreeNode(o); - while (true) { - if (res.getData().compareTo(p.getData()) < 0) { - if (p.left == null) { - p.setLeft(res); - break; - } - p = p.left; - } else if (res.getData().compareTo(p.getData()) > 0) { - if (p.right == null) { - p.setRight(res); - break; - } - p = p.right; - } else { - return null; - } - } - size++; - } - return res; - } - - - - public ArrayList preOrderTraversal(BinaryTreeNode node) { - - if (node != null) { - preOrderTraversal(node.left); - myList.add(node.data); - preOrderTraversal(node.right); - } - return myList; - } + + public boolean isEmpty() { + return data == null; + } + + public int size() { + return size; + } + + public BinaryTreeNode insert(E o) { + BinaryTreeNode res; + if (isEmpty()) { + data = o; + size++; + return this; + } else { + BinaryTreeNode p = this; + res = new BinaryTreeNode(o); + while (true) { + if (res.getData().compareTo(p.getData()) < 0) { + if (p.left == null) { + p.setLeft(res); + break; + } + p = p.left; + } else if (res.getData().compareTo(p.getData()) > 0) { + if (p.right == null) { + p.setRight(res); + break; + } + p = p.right; + } else { + return null; + } + } + size++; + } + return res; + } + + public ArrayList preOrderTraversal(BinaryTreeNode node) { + + if (node != null) { + preOrderTraversal(node.left); + myList.add(node.data); + preOrderTraversal(node.right); + } + return myList; + } @Override public String toString() { @@ -82,18 +78,23 @@ public String toString() { public E getData() { return data; } + public void setData(E data) { this.data = data; } + public BinaryTreeNode getLeft() { return left; } + public void setLeft(BinaryTreeNode left) { this.left = left; } + public BinaryTreeNode getRight() { return right; } + public void setRight(BinaryTreeNode right) { this.right = right; } @@ -105,7 +106,7 @@ public int hashCode() { result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } - + @Override public boolean equals(Object obj) { if (this == obj) diff --git a/group12/382266293/coding/basic/collection/concrete/LinkedList.java b/group12/382266293/coding/basic/collection/concrete/LinkedList.java new file mode 100644 index 0000000000..f5ce66247e --- /dev/null +++ b/group12/382266293/coding/basic/collection/concrete/LinkedList.java @@ -0,0 +1,548 @@ +package collection.concrete; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; + +import static util.TestUtil.*; +import static util.Print.*; +import collection.AbstractList; +import collection.Iterator; + +public class LinkedList extends AbstractList { + + private Node head; + private int size; + + public LinkedList() { + this.head = new Node(null); + this.size = 0; + } + + /** + * 把该链表逆置 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + + @SuppressWarnings("unchecked") + public void reverse() { + if (head == null) { + return; + } + Node pre = head; + Node cur = head.next; + Node next; + while (cur != null) { + next = cur.next; + cur.next = pre; + pre = cur; + cur = next; + } + head.next = null; + head = pre; + + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + * + */ + public void removeFirstHalf() { + int deleteLength = size / 2; + remove(0, deleteLength); + } + + private void clearAndSetNewHead(int deleteIndex) { + Node x = head; + for (int i = 0; i < deleteIndex; i++) { + Node next = x.next; + x.data = null; + x.next = null; + x = next; + size--; + if (i == deleteIndex - 1) + head = next; + } + } + + private void clearAndSetNewHead(Node node, int deleteLength) { + Node x = node; + for (int i = 0; i < deleteLength; i++) { + Node next = x.next; + x.data = null; + x.next = null; + x = next; + size--; + if (i == deleteLength - 1) + node = next; + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + checkIndex(i); + checkIndex(i + length); + + if (i == 0) { + clearAndSetNewHead(length); + return; + } + Node pre = getNode(i - 1); + Node x = pre.next; + checkIndex(length + i); + for (int j = 0; j < length; j++) { + Node next = x.next; + x.data = null; + x.next = null; + x = next; + size--; + if (i == length - 1) + pre.next = next; + } + } + + /** + * 假定当前链表和list均包含已升序排列的整数 从当前链表中取出那些list所指定的元素 例如当前链表 = + * 11->101->201->301->401->501->601->701 listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * + * @param list + */ + public int[] getElements(LinkedList list) { + + if (size() == 0 || list.size() == 0) { + return new int[0]; + } + + Iterator it2 = list.iterator(); + int size = list.size(); + int[] result = new int[size]; + int curr = (int) it2.next(); + Node start = getNode(curr); + result[0] = (int) start.data; + int next, batch; + int res = -1; + for (int i = 1; i < size; i++) { + next = (int) it2.next(); + batch = next - curr; + Node p = start; + for (int j = 0; j < batch; j++) { + p = p.next; + } + result[i] = (int) p.data; + start = p; + curr = next; + } + return result; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 从当前链表中中删除在list中出现的元素 + * + * @param list + */ + + public void subtract2(LinkedList list) { + LinkedList result = new LinkedList<>(); + + if (list.size == 0 || this.size == 0) { + return; + } + + Node n1 = this.head; + Node n2 = list.head; + Node curr_list = list.head; + for (int i = 0; i < this.size; i++, n1 = n1.next) { + boolean equals = false; + curr_list = list.head; + while(curr_list != null && !equals) { + if (Objects.equals(n1.data, curr_list.data)) { + equals = true; + } + curr_list = curr_list.next; + } + + if (!equals) { + result.add(n1.data); + } + + } + + clearAndSetNewHead(this.size); + Node p2 = result.head; + while(p2.next != null) { + add(p2.data); + p2 = p2.next; + } + add(p2.data); + this.size = result.size; + + } + + + + + public void subtract(LinkedList list) { + + Node n1 = list.getNode(0); + Node n2 = head; + int count = list.size(); + int index = 0; + int iR = 0; + while (count != 0 && n1 != null && n2 != null) { + + while (count > 1 && Objects.equals(n1.data, n1.next.data)) { + n1 = n1.next; + count--; + } + + while (Objects.equals(n1.data, n2.data) == false) { + index++; + if (index > size() - 1) + return; + n2 = n2.next; + } + iR = index; + + while (n2 != null && Objects.equals(n1.data, n2.data)) { + remove(iR); + count--; + n2 = n2.next; + } + index = iR; + n1 = n1.next; + } + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + Node n1 = head; + int count = size(); + int index = 0; + int iR = 0; + while (count > 1 && n1 != null) { + while (count > 1 && Objects.equals(n1.data, n1.next.data) == false) { + n1 = n1.next; + index++; + count--; + } + iR = index; + + while (count > 1 && Objects.equals(n1.data, n1.next.data)) { + remove(iR); + n1 = n1.next; + count--; + } + index = iR; + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + if (min >= max) { + throw new IllegalArgumentException(min + " is greater than " + max); + } + + if (size() == 0) { + return; + } + + Node curr = head; + if ((int) head.data > min) { + curr = curr.next; + } + + Node p = head; + while ((int) curr.data <= min) { + p = curr; + curr = curr.next; + } + + Node next = curr; + for (Node x = curr; (int) x.data < max;) { + next = x.next; + x.data = null; + x.next = null; + x = next; + size--; + } + + if ((int) p.data > min) { + head = next; + size--; + } else { + p.next = next; + } + } + + public static void main(String args[]) { + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + + public LinkedList intersection(LinkedList list) { + + LinkedList result = new LinkedList(); + Node n1 = list.getNode(0); + Node n2 = head; + + int count = list.size(); + int index = 0; + int iR = 0; + while (count != 0 && n1 != null && n2 != null) { + + while (Objects.equals(n1.data, n2.data) == false) { + index++; + if (index > size() - 1) + return result; + n2 = n2.next; + } + iR = index; + + if (n2 != null && Objects.equals(n1.data, n2.data)) { + result.add(n1.data); + count--; + n2 = n2.next; + } + index = iR; + n1 = n1.next; + } + + return result; + + } + + public void removeDuplicateValues2() { + Node n1 = head; + int count = size(); + int index = 0; + int iR = 0; + while (count > 1 && n1 != null) { + while (count > 1 && Objects.equals(n1.data, n1.next.data) == false) { + n1 = n1.next; + index++; + count--; + } + iR = index; + + while (count > 1 && Objects.equals(n1.data, n1.next.data)) { + Node next = n1.next.next; + n1.next.data = null; + n1.next = null; + n1 = n1.next; + n1.next = next; + count--; + } + index = iR; + + } + } + + @Override + public void add(E e) { + addLast(e); + } + + @Override + public E get(int index) { + checkIndex(index); + return getNode(index).data; + } + + public E getFirst() { + return get(0); + } + + public E getLast() { + return get(size - 1); + } + + public void add(int index, E e) { + if (index == size) { + addLast(e); + return; + } + + if (index == 0) { + addFirst(e); + return; + } + + checkIndex(index); + Node pNode = new Node(e); + Node p = getNode(index); + synchronized (this) { + getNode(index - 1).next = pNode; + pNode.next = p; + size++; + } + } + + public void addFirst(E e) { + checkCapacity(); + Node pNode = new Node(e); + Node oldHead = head; + head = pNode; + pNode.next = oldHead; + size++; + return; + } + + public void addLast(E e) { + if (size == 0) { + addFirst(e); + return; + } + + checkCapacity(); + Node res = new Node(e); + setLastNode(res); + size++; + return; + } + + public E removeFirst() { + return remove(0); + } + + public E removeLast() { + return remove(size - 1); + } + + @SuppressWarnings("unchecked") + public E remove(int index) { + checkIndex(index); + Node pNode = null; + E data = null; + if (index == 0) { + data = (E) head.data; + head = head.next; + } else if (index == size - 1) { + pNode = getNode(index - 1); + data = (E) pNode.next.data; + pNode.next = null; + } else { + pNode = head; + for (int i = 0; i < index - 1; i++) { + pNode = pNode.next; + } + data = (E) pNode.next.data; + pNode.next = pNode.next.next; + } + size--; + return data; + } + + @Override + public int size() { + return size; + } + + @Override + public Iterator iterator() { + return new LinkedListIterator(this); + } + + private void checkCapacity() { + if (size > MAX_SIZE) + throw new IndexOutOfBoundsException("Reached max capacity: " + MAX_SIZE); + } + + private Node getNode(int index) { + if (size == 0) + return head; + + Node pNode = head; + for (int i = 0; i < index; i++) { + pNode = pNode.next; + } + return pNode; + } + + private void setLastNode(Node res) { + getNode(size - 1).next = res; + } + + private static class Node { + E data; + Node next; + + public Node(E data) { + this.data = data; + this.next = null; + } + + @Override + public String toString() { + return data.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Node other = (Node) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + return true; + } + } + + @SuppressWarnings("hiding") + private class LinkedListIterator implements Iterator { + + private LinkedList myLinkedList; + private int pos; + + public LinkedListIterator(LinkedList linkedList) { + myLinkedList = linkedList; + pos = 0; + } + + @Override + public boolean hasNext() { + return pos < size; + } + + @Override + public E next() { + if (hasNext()) + return (E) get(pos++); + throw new NoSuchElementException(); + } + } +} diff --git a/group12/382266293/src/Collection/Concrete/Queue.java b/group12/382266293/coding/basic/collection/concrete/Queue.java similarity index 85% rename from group12/382266293/src/Collection/Concrete/Queue.java rename to group12/382266293/coding/basic/collection/concrete/Queue.java index 300fb633af..d9313b1c6e 100644 --- a/group12/382266293/src/Collection/Concrete/Queue.java +++ b/group12/382266293/coding/basic/collection/concrete/Queue.java @@ -1,22 +1,21 @@ -package Collection.Concrete; -import java.util.NoSuchElementException; +package collection.concrete; -import Collection.AbstractList; -import Collection.Iterator; +import collection.AbstractList; +import collection.Iterator; public class Queue extends AbstractList { - + private LinkedList myList; public Queue() { this.myList = new LinkedList(); } - - public void enQueue(E e){ + + public void enQueue(E e) { myList.addLast(e); } - - public E deQueue(){ + + public E deQueue() { if (0 == size()) return null; return myList.removeFirst(); @@ -26,26 +25,25 @@ public E deQueue(){ public void add(E e) { enQueue(e); } - + @Override public E get(int index) { if (0 == size()) return null; return myList.get(index); } - + public E element() { if (0 == size()) return null; return myList.getFirst(); } - @Override public int size() { return myList.size(); } - + @Override protected Iterator iterator() { return myList.iterator(); @@ -76,9 +74,4 @@ public boolean equals(Object obj) { return true; } - - - - - } diff --git a/group12/382266293/src/Collection/Concrete/Stack.java b/group12/382266293/coding/basic/collection/concrete/Stack.java similarity index 89% rename from group12/382266293/src/Collection/Concrete/Stack.java rename to group12/382266293/coding/basic/collection/concrete/Stack.java index 17ec4364fa..6fe1e20d47 100644 --- a/group12/382266293/src/Collection/Concrete/Stack.java +++ b/group12/382266293/coding/basic/collection/concrete/Stack.java @@ -1,39 +1,40 @@ -package Collection.Concrete; +package collection.concrete; import java.util.EmptyStackException; import java.util.NoSuchElementException; -import Collection.AbstractList; -import Collection.Iterator; +import collection.AbstractList; +import collection.Iterator; public class Stack extends AbstractList { - + private ArrayList myList; public Stack() { this.myList = new ArrayList(); } - public void push(E e){ + public void push(E e) { myList.addLast(e); } - - public E pop(){ + + public E pop() { checkEmpty(); return myList.removeLast(); } - + private void checkEmpty() { if (0 == size()) throw new EmptyStackException(); } - public E peek(){ + public E peek() { checkEmpty(); return myList.getLast(); } - public int size(){ + @Override + public int size() { return myList.size(); } @@ -47,7 +48,7 @@ public E get(int index) { checkEmpty(); return myList.get(size() - index - 1); } - + @Override protected Iterator iterator() { return new StackIterator(myList); @@ -77,12 +78,12 @@ public boolean equals(Object obj) { return false; return true; } - + private class StackIterator implements Iterator { private ArrayList myArrayList; private int pos; - + public StackIterator(ArrayList myList) { myArrayList = myList; pos = 0; @@ -101,6 +102,4 @@ public E next() { } } - - } diff --git a/group12/382266293/src/TestCollection/AllTests.java b/group12/382266293/coding/basic/test/collection/AllTests.java similarity index 91% rename from group12/382266293/src/TestCollection/AllTests.java rename to group12/382266293/coding/basic/test/collection/AllTests.java index cd4eeadb58..661d6c3722 100644 --- a/group12/382266293/src/TestCollection/AllTests.java +++ b/group12/382266293/coding/basic/test/collection/AllTests.java @@ -1,4 +1,4 @@ -package TestCollection; +package test.collection; import org.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/group12/382266293/src/TestCollection/ArrayListTest.java b/group12/382266293/coding/basic/test/collection/ArrayListTest.java similarity index 64% rename from group12/382266293/src/TestCollection/ArrayListTest.java rename to group12/382266293/coding/basic/test/collection/ArrayListTest.java index f29580616f..f57167bbd3 100644 --- a/group12/382266293/src/TestCollection/ArrayListTest.java +++ b/group12/382266293/coding/basic/test/collection/ArrayListTest.java @@ -1,6 +1,5 @@ -package TestCollection; +package test.collection; -import static util.Print.*; import static util.TestUtil.*; import java.util.Date; import java.util.NoSuchElementException; @@ -10,26 +9,26 @@ import org.junit.Before; import org.junit.Test; - -import Collection.Iterator; -import Collection.List; -import Collection.Concrete.ArrayList; +import collection.Iterator; +import collection.List; +import collection.concrete.ArrayList; import junit.framework.TestCase; public class ArrayListTest extends TestCase { - private ArrayList myAL; private static Random rnd = new Random(); - + + @Override @Before public void setUp() throws Exception { - + myAL = new ArrayList(); - assertEquals(true,myAL.isEmpty()); - + assertEquals(true, myAL.isEmpty()); + } + @Override @After public void tearDown() throws Exception { myAL = null; @@ -37,7 +36,7 @@ public void tearDown() throws Exception { @Test public void testRawTypeArrayList() { - + List rawList = new ArrayList(); assertEquals(rawList.size(), 0); rawList.add(new Date()); @@ -46,49 +45,49 @@ public void testRawTypeArrayList() { @Test public void testEmpty() { - - assertEquals(true,myAL.isEmpty()); - + + assertEquals(true, myAL.isEmpty()); + myAL.add(5); - assertEquals(false,myAL.isEmpty()); - + assertEquals(false, myAL.isEmpty()); + int num = getRandomNumber(); addIntWithNatureOrder(myAL, num); - assertEquals(false,myAL.isEmpty()); - + assertEquals(false, myAL.isEmpty()); + } @Test public void testAddIntAutoBoxing() { - + myAL.add(5); myAL.add(5); myAL.add(5); - myAL.add(1,10); + myAL.add(1, 10); int c = myAL.get(1); - assertEquals(10,c); - - assertEquals(4,myAL.size()); - myAL.add(4,15); + assertEquals(10, c); + + assertEquals(4, myAL.size()); + myAL.add(4, 15); int a = myAL.get(0); Integer b = myAL.get(1); - c = myAL.get(2); + c = myAL.get(2); int d = myAL.get(3); int e = myAL.get(4); - assertEquals(5,a); - assertEquals(new Integer(10),b); - assertEquals(5,c); - assertEquals(5,d); - assertEquals(15,e); + assertEquals(5, a); + assertEquals(new Integer(10), b); + assertEquals(5, c); + assertEquals(5, d); + assertEquals(15, e); } - + @Test public void testGet() { - + int[] result = addRandomInt(myAL, getRandomNumber()); - - int actual,expected; - + + int actual, expected; + for (int i = 0; i < result.length; i++) { actual = myAL.get(i); expected = result[i]; @@ -101,7 +100,7 @@ public void testGet() { public void testRemove() { addIntWithNatureOrder(myAL, 100); - + testRemoveAndGetFromTail(myAL); try { myAL.remove(10); @@ -114,59 +113,56 @@ public void testRemove() { @Test public void testSize() { - - assertEquals(0,myAL.size()); + + assertEquals(0, myAL.size()); int num = getRandomNumber(); addIntWithNatureOrder(myAL, num); - assertEquals(num,myAL.size()); + assertEquals(num, myAL.size()); } - - @Test public void testGrow() { - + int actualSize = 12345; - + addIntWithNatureOrder(myAL, actualSize); - - assertEquals(actualSize,myAL.size()); + + assertEquals(actualSize, myAL.size()); } - @Test public void testIterator() { - - addIntWithNatureOrder(myAL,100); - + + addIntWithNatureOrder(myAL, 100); + Iterator it = myAL.iterator(); - for(int i = 0; it.hasNext(); i++){ + for (int i = 0; it.hasNext(); i++) { int actual = it.next(); - assertEquals(i,actual); + assertEquals(i, actual); } - - try { + + try { it.next(); - } catch (NoSuchElementException ex) { - assertEquals(ex.getClass(),NoSuchElementException.class); - } + } catch (NoSuchElementException ex) { + assertEquals(ex.getClass(), NoSuchElementException.class); + } } - + @Test public void testIndexOf() { - + int num = 200; - addIntWithNatureOrder(myAL,num); + addIntWithNatureOrder(myAL, num); - int expected,actual; - for (int i = 0; i < num-1; i++) { + int expected, actual; + for (int i = 0; i < num - 1; i++) { expected = i; actual = myAL.indexOf(i); assertEquals(expected, actual); } - - assertEquals(-1, myAL.indexOf(-1*getRandomNumber())); + + assertEquals(-1, myAL.indexOf(-1 * getRandomNumber())); } diff --git a/group12/382266293/src/TestCollection/BinaryTreeNodeTest.java b/group12/382266293/coding/basic/test/collection/BinaryTreeNodeTest.java similarity index 71% rename from group12/382266293/src/TestCollection/BinaryTreeNodeTest.java rename to group12/382266293/coding/basic/test/collection/BinaryTreeNodeTest.java index 275ef59484..0aeda8dc03 100644 --- a/group12/382266293/src/TestCollection/BinaryTreeNodeTest.java +++ b/group12/382266293/coding/basic/test/collection/BinaryTreeNodeTest.java @@ -1,7 +1,5 @@ -package TestCollection; +package test.collection; -import static util.Print.*; -import java.util.Random; import java.util.Set; import java.util.TreeSet; import static util.TestUtil.*; @@ -9,19 +7,21 @@ import org.junit.Before; import org.junit.Test; -import Collection.Concrete.BinaryTreeNode; +import collection.concrete.BinaryTreeNode; import junit.framework.TestCase; public class BinaryTreeNodeTest extends TestCase { private BinaryTreeNode myTree; - + + @Override @Before public void setUp() throws Exception { myTree = new BinaryTreeNode(); assertEquals(0, myTree.size()); } + @Override @After public void tearDown() throws Exception { myTree = null; @@ -29,26 +29,26 @@ public void tearDown() throws Exception { @Test public void testInsert() { - Set expected = new TreeSet(); + Set expected = new TreeSet(); int size = getRandomNumber(); - int j = 0 ; + int j = 0; while (expected.size() != size) { j = getRandomNumber(); expected.add(j); myTree.insert(j); } - - assertEquals(size,myTree.size()); - assertEquals(expected.toString(),myTree.toString()); + + assertEquals(size, myTree.size()); + assertEquals(expected.toString(), myTree.toString()); } - + public void testSize() { - + for (int i = 0; i < getRandomNumber(); i++) { myTree.insert(18); myTree.insert(-19); myTree.insert(1); - assertEquals(3,myTree.size()); - } + assertEquals(3, myTree.size()); + } } } \ No newline at end of file diff --git a/group12/382266293/src/TestCollection/LinkedListTest.java b/group12/382266293/coding/basic/test/collection/LinkedListTest.java similarity index 56% rename from group12/382266293/src/TestCollection/LinkedListTest.java rename to group12/382266293/coding/basic/test/collection/LinkedListTest.java index 8b9fad15eb..779216d810 100644 --- a/group12/382266293/src/TestCollection/LinkedListTest.java +++ b/group12/382266293/coding/basic/test/collection/LinkedListTest.java @@ -1,29 +1,29 @@ -package TestCollection; +package test.collection; -import static util.Print.*; -import static util.TestUtil.*; +import static util.TestUtil.*; import java.util.Date; import java.util.NoSuchElementException; import org.junit.After; import org.junit.Before; import org.junit.Test; -import Collection.Iterator; -import Collection.List; -import Collection.Concrete.LinkedList; +import collection.Iterator; +import collection.List; +import collection.concrete.LinkedList; import junit.framework.TestCase; - public class LinkedListTest extends TestCase { LinkedList myLL; - + + @Override @Before public void setUp() throws Exception { myLL = new LinkedList(); - assertEquals(0,myLL.size()); + assertEquals(0, myLL.size()); } + @Override @After public void tearDown() throws Exception { myLL = null; @@ -35,178 +35,192 @@ public void testLinkedList() { assertEquals(rawList.size(), 0); rawList.add(new Date()); assertEquals(1, rawList.size()); - + + } + + @Test + public void testReverse() { + addString(myLL, 5); + myLL.reverse(); + } + + @Test + public void testRemoveFirstHalf() { + addString(myLL, 5); + myLL.removeFirstHalf(); + assertEquals(3, myLL.size()); + assertEquals("2", myLL.get(0)); + assertEquals("3", myLL.get(1)); + assertEquals("4", myLL.get(2)); } @Test public void testAddE() { myLL.add("s"); - assertEquals(1,myLL.size()); - assertEquals(false,myLL.isEmpty()); + assertEquals(1, myLL.size()); + assertEquals(false, myLL.isEmpty()); } @Test public void testAddStringE() { String a; - - addString(myLL,30); - println(myLL.get(0)); - -// for (int i = 0 ; i < 29; i++) { -// a = "" + i; -// assertEquals(myLL.get(i),a); -// } + + addString(myLL, 30); + + // for (int i = 0 ; i < 29; i++) { + // a = "" + i; + // assertEquals(myLL.get(i),a); + // } } - + @Test public void testAddIndex() { String a; - for (int i = 0 ; i < 30; i++) { + for (int i = 0; i < 30; i++) { a = "" + i; myLL.add(a); } - + String ss = "ss"; - myLL.add(3,ss); + myLL.add(3, ss); assertEquals(myLL.get(3), ss); assertEquals(myLL.get(2), "2"); assertEquals(myLL.get(4), "3"); - + } - + public void testAddFirst() { String a; - for (int i = 0 ; i < 20; i++) { + for (int i = 0; i < 20; i++) { a = "" + i; myLL.add(a); } - + String ss = "bba"; myLL.addFirst(ss); - assertEquals(ss,myLL.get(0)); + assertEquals(ss, myLL.get(0)); assertEquals(21, myLL.size()); - + ; - for (int i = 1 ; i < myLL.size(); i++) { - a = (i-1) + ""; + for (int i = 1; i < myLL.size(); i++) { + a = (i - 1) + ""; assertEquals(a, myLL.get(i)); - } + } } - + public void testAddLast() { String a; - for (int i = 0 ; i < 25; i++) { + for (int i = 0; i < 25; i++) { a = "" + i; myLL.add(a); } - + String ss = "25"; myLL.addLast(ss); int size = myLL.size(); assertEquals(26, size); - for (int i = 0 ; i < size; i++) { + for (int i = 0; i < size; i++) { a = i + ""; assertEquals(a, myLL.get(i)); - } + } } - + @Test public void testRemoveFirst() { - + String a = ""; String result = ""; - for(int i = 0; i < 10; i++) { - myLL.add(i+""); + for (int i = 0; i < 10; i++) { + myLL.add(i + ""); } - + myLL.removeFirst(); assertEquals(9, myLL.size()); - for(int i = 0; i < myLL.size(); i++) { - a = i+1 + ""; + for (int i = 0; i < myLL.size(); i++) { + a = i + 1 + ""; assertEquals(a, myLL.get(i)); } - + int size = myLL.size(); - for(int i = 0; i < size; i++) { - a = i+1 +""; + for (int i = 0; i < size; i++) { + a = i + 1 + ""; result = myLL.removeFirst(); assertEquals(a, result); } - + assertEquals(0, myLL.size()); } - + @Test public void testRemoveLast() { - + String a = ""; String result = ""; - for(int i = 0; i < 10; i++) { - myLL.add(i+""); + for (int i = 0; i < 10; i++) { + myLL.add(i + ""); } - + myLL.removeLast(); assertEquals(9, myLL.size()); - for(int i = 0; i < myLL.size(); i++) { + for (int i = 0; i < myLL.size(); i++) { a = i + ""; assertEquals(a, myLL.get(i)); } - + int size = myLL.size(); - for(int i = 0; i < size; i++) { - a = myLL.size()-1 +""; + for (int i = 0; i < size; i++) { + a = myLL.size() - 1 + ""; result = myLL.removeLast(); assertEquals(a, result); } - + assertEquals(0, myLL.size()); - + } - @Test public void testRemove() { - + String res = ""; String a = ""; - for(int i = 0; i < 10; i++) { - myLL.add(i+""); + for (int i = 0; i < 10; i++) { + myLL.add(i + ""); } - for(int i = myLL.size()-1; i >= 0; i--) { + for (int i = myLL.size() - 1; i >= 0; i--) { a = myLL.get(i); res = myLL.remove(i); assertEquals(i, myLL.size()); - assertEquals(a,res); + assertEquals(a, res); } + } @Test public void testSize() { - assertEquals(0,myLL.size()); + assertEquals(0, myLL.size()); } @Test public void testIterator() { - for(int i = 0; i<10; i++) { - myLL.add(i+""); + for (int i = 0; i < 10; i++) { + myLL.add(i + ""); } Iterator it = myLL.iterator(); - - for(int i = 0; it.hasNext(); i++){ + + for (int i = 0; it.hasNext(); i++) { String res = it.next(); - assertEquals(i+"",res); + assertEquals(i + "", res); } - - try { + + try { it.next(); - } catch (NoSuchElementException ex) { - assertEquals(ex.getClass(),NoSuchElementException.class); - } + } catch (NoSuchElementException ex) { + assertEquals(ex.getClass(), NoSuchElementException.class); + } } - } diff --git a/group12/382266293/coding/basic/test/collection/LinkedListTest2.java b/group12/382266293/coding/basic/test/collection/LinkedListTest2.java new file mode 100644 index 0000000000..490da017d6 --- /dev/null +++ b/group12/382266293/coding/basic/test/collection/LinkedListTest2.java @@ -0,0 +1,243 @@ +package test.collection; + +import static util.Print.*; +import static util.TestUtil.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import collection.concrete.LinkedList; +import junit.framework.TestCase; + +public class LinkedListTest2 extends TestCase { + + LinkedList myLL; + + @Override + @Before + public void setUp() throws Exception { + myLL = new LinkedList(); + assertEquals(0, myLL.size()); + } + + @Override + @After + public void tearDown() throws Exception { + myLL = null; + } + + @Test + public void testReverse() { + addIntWithNatureOrder(myLL, 5); + myLL.reverse(); + for (int i = 0; i < 5; i++) { + int acutal = myLL.get(i); + assertEquals(4 - i, acutal); + } + } + + @Test + public void testRemoveFirstHalf() { + myLL = new LinkedList(); + addIntWithNatureOrder(myLL, 5); + myLL.removeFirstHalf(); + assertEquals(3, myLL.size()); + assertEquals(2, (int) myLL.get(0)); + assertEquals(3, (int) myLL.get(1)); + assertEquals(4, (int) myLL.get(2)); + + myLL = new LinkedList(); + myLL.removeFirstHalf(); + assertEquals(0, myLL.size()); + + } + + @Test + public void testRemove2() { + addIntWithNatureOrder(myLL, 5); + myLL.remove(1, 2); + assertEquals(3, myLL.size()); + assertEquals(0, (int) myLL.get(0)); + assertEquals(3, (int) myLL.get(1)); + assertEquals(4, (int) myLL.get(2)); + + myLL = new LinkedList(); + try { + myLL.remove(1, 2); + } catch (IndexOutOfBoundsException e) { + + } + + assertEquals(0, myLL.size()); + + } + + @Test + public void testGetElements() { + addIntWithNatureOrder(myLL, 10); + LinkedList list = new LinkedList(); + list.add(0); + list.add(2); + list.add(7); + int[] result = myLL.getElements(list); + for (int i = 0; i < result.length; i++) { + int expected = list.get(i); + int actual = result[i]; + assertEquals(expected, actual); + } + + myLL = new LinkedList(); + result = myLL.getElements(list); + assertEquals(0, myLL.size()); + + } + + @Test + public void testSubstract() { + LinkedList myLL = new LinkedList(); + addIntWithNatureOrder(myLL, 10); + myLL.add(10); + myLL.add(10); + myLL.add(12); + LinkedList list = new LinkedList(); + list.add(0); + list.add(0); + addIntWithNatureOrder(list, 10); + list.add(10); + list.add(12); + list.add(22); + myLL.subtract(list); + assertEquals(0, myLL.size()); + + myLL = new LinkedList(); + list = new LinkedList(); + myLL.subtract(list); + assertEquals(0, myLL.size()); + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testSubstract2() { + LinkedList myLL = new LinkedList(); + addIntWithNatureOrder(myLL, 10); + myLL.add(10); + myLL.add(10); + myLL.add(12); + LinkedList list = new LinkedList(); + list.add(0); + list.add(0); + addIntWithNatureOrder(list, 10); + list.add(10); + list.add(12); + list.add(22); + + myLL.subtract2(list); + assertEquals(0, myLL.size()); + + myLL = new LinkedList(); + LinkedList list1 = new LinkedList(); + myLL.subtract2(list); + assertEquals(0, myLL.size()); + + addIntWithNatureOrder(myLL, 10); + myLL.add(-3); + println(myLL); + list1.add(10); + list1.add(3); + list1.add("dd"); + list1.add(null); + list1.add(-3); + list1.add(9); + list1.add(0); + myLL.subtract2(list1); + + assertEquals("[1, 2, 4, 5, 6, 7, 8]",myLL.toString()); + + } + + + + @Test + public void testIntersection() { + + LinkedList list = new LinkedList(); + LinkedList result = myLL.intersection(list); + assertEquals(0, result.size()); + + addIntWithNatureOrder(myLL, 10); + myLL.add(10); + myLL.add(12); + myLL.add(13); + myLL.add(24); + + list.add(0); + list.add(5); + list.add(10); + result = myLL.intersection(list); + assertEquals(0, (int) result.get(0)); + assertEquals(5, (int) result.get(1)); + assertEquals(10, (int) result.get(2)); + + myLL = new LinkedList(); + result = new LinkedList(); + myLL.intersection(list); + assertEquals(0, result.size()); + + } + + @Test + public void testRemoveDuplicateValues() { + + myLL.add(0); + myLL.add(0); + myLL.add(1); + myLL.add(1); + myLL.add(10); + myLL.removeDuplicateValues(); + assertEquals(3, myLL.size()); + assertEquals(0, (int) myLL.get(0)); + assertEquals(1, (int) myLL.get(1)); + assertEquals(10, (int) myLL.get(2)); + + myLL = new LinkedList(); + myLL.removeDuplicateValues(); + assertEquals(0, myLL.size()); + + } + + @Test + public void testRemoveRange() { + + myLL.add(0); + addIntWithNatureOrder(myLL, 10); + myLL.add(9); + myLL.add(10); + myLL.add(12); + myLL.add(13); + myLL.add(24); + + myLL.removeRange(-5, 3); + assertEquals(3, (int) myLL.get(0)); + + myLL.removeRange(3, 4); + assertEquals(3, (int) myLL.get(0)); + + myLL.removeRange(3, 5); + assertEquals(3, (int) myLL.get(0)); + assertEquals(5, (int) myLL.get(1)); + + myLL.removeRange(-3, 11); + assertEquals(12, (int) myLL.get(0)); + + myLL = new LinkedList(); + myLL.removeRange(-1, 10); + assertEquals(0, myLL.size()); + + } + + + + +} diff --git a/group12/382266293/src/TestCollection/QueueTest.java b/group12/382266293/coding/basic/test/collection/QueueTest.java similarity index 88% rename from group12/382266293/src/TestCollection/QueueTest.java rename to group12/382266293/coding/basic/test/collection/QueueTest.java index 01a9aa31f2..f52c0d1563 100644 --- a/group12/382266293/src/TestCollection/QueueTest.java +++ b/group12/382266293/coding/basic/test/collection/QueueTest.java @@ -1,22 +1,26 @@ -package TestCollection; +package test.collection; -import static util.Print.*; import org.junit.After; import org.junit.Before; import org.junit.Test; + +import collection.concrete.Queue; + import static util.TestUtil.*; -import Collection.Concrete.Queue; + import junit.framework.TestCase; public class QueueTest extends TestCase { private Queue myQueue; - + + @Override @Before public void setUp() throws Exception { - myQueue= new Queue(); + myQueue = new Queue(); } + @Override @After public void tearDown() throws Exception { myQueue = null; @@ -33,20 +37,20 @@ public void testIsEmpty() { public void testEnQueue() { enQueueIntWithNatureOrder(myQueue, getRandomNumber()); - + } @Test public void testDeQueue() { enQueueIntWithNatureOrder(myQueue, getRandomNumber()); int size = myQueue.size(); - for (int i = 0; i < size ; i++) { - assertEquals(size-i, myQueue.size()); + for (int i = 0; i < size; i++) { + assertEquals(size - i, myQueue.size()); int expect = i; int actual = myQueue.deQueue(); assertEquals(expect, actual); } - + assertEquals(null, myQueue.deQueue()); assertEquals(null, myQueue.element()); assertEquals(null, myQueue.get(0)); @@ -55,25 +59,25 @@ public void testDeQueue() { @Test public void testelement() { - + int expected = 0; int element1 = 0; int repeated = 0; - + for (int i = 0; i < 10; i++) { myQueue.enQueue(i); expected = i; - + element1 = myQueue.element(); assertEquals(expected, element1); - + for (int j = 0; j < i; j++) { repeated = myQueue.element(); assertEquals(expected, repeated); } myQueue.deQueue(); } - + } @Test @@ -94,5 +98,4 @@ public void testAdd() { } } - } diff --git a/group12/382266293/src/TestCollection/StackTest.java b/group12/382266293/coding/basic/test/collection/StackTest.java similarity index 79% rename from group12/382266293/src/TestCollection/StackTest.java rename to group12/382266293/coding/basic/test/collection/StackTest.java index 3784a9b972..75b3732511 100644 --- a/group12/382266293/src/TestCollection/StackTest.java +++ b/group12/382266293/coding/basic/test/collection/StackTest.java @@ -1,6 +1,4 @@ -package TestCollection; - -import static util.Print.*; +package test.collection; import java.util.EmptyStackException; import static util.TestUtil.*; @@ -8,18 +6,20 @@ import org.junit.Before; import org.junit.Test; -import Collection.Concrete.Stack; +import collection.concrete.Stack; import junit.framework.TestCase; public class StackTest extends TestCase { Stack myStack; - + + @Override @Before public void setUp() throws Exception { - myStack= new Stack(); + myStack = new Stack(); } + @Override @After public void tearDown() throws Exception { myStack = null; @@ -46,12 +46,12 @@ public void testPop() { int size = myStack.size(); for (int i = size; i > 0; i--) { assertEquals(i, myStack.size()); - int expect = i-1; + int expect = i - 1; assertEquals(i, myStack.size()); int actual = myStack.pop(); assertEquals(expect, actual); } - + try { myStack.pop(); fail("no exception throw"); @@ -62,36 +62,35 @@ public void testPop() { @Test public void testPeek() { - + int expected = 0; int peek1 = 0; int repeated = 0; - + for (int i = 0; i < 10; i++) { myStack.push(i); expected = i; - + peek1 = myStack.peek(); assertEquals(expected, peek1); - + for (int j = 0; j < i; j++) { repeated = myStack.peek(); assertEquals(expected, repeated); } } - + } - - + public void testGet() { - + try { myStack.get(getRandomNumber()); fail("no exception throw"); } catch (Exception e) { assertEquals(EmptyStackException.class, e.getClass()); } - + } @Test @@ -104,13 +103,22 @@ public void testSize() { @Test public void testAdd() { - myStack.push(5); - myStack.push(10); - myStack.push(15); - println(myStack.get(0)); - println(myStack.get(1)); - println(myStack.get(2)); - + + int size = getRandomNumber(); + int[] expected = new int[size]; + int actual; + for (int i = 0; i < size; i++) { + actual = getRandomNumber(); + expected[i] = actual; + myStack.add(actual); + } + + int expectedInt; + for (int i = 0; i < size; i++) { + expectedInt = expected[size - i - 1]; + actual = myStack.pop(); + assertEquals(expectedInt, actual); + } } @Test diff --git a/group12/382266293/coding/basic/util/ActionXMLreader.java b/group12/382266293/coding/basic/util/ActionXMLreader.java new file mode 100644 index 0000000000..23e024c088 --- /dev/null +++ b/group12/382266293/coding/basic/util/ActionXMLreader.java @@ -0,0 +1,50 @@ +package util; + +import java.util.List; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.Node; +import org.dom4j.io.SAXReader; + +public class ActionXMLreader { + + public Node getRootNode(String add) { + SAXReader reader = new SAXReader(); + Document document = null; + Node root = null; + try { + document = reader.read(add); + root = document.getRootElement(); + } catch (DocumentException e) { + e.printStackTrace(); + } + return root; + } + + public String parseClass(Node root, String attr) { + + @SuppressWarnings("rawtypes") + List list = root.selectNodes("action[@name='" + attr + "']"); + String clazz = null; + for (Object o : list) { + Element e = (Element) o; + clazz = e.attributeValue("class"); + } + return clazz; + } + + public String parseResult(Node root, String attr, String result) { + + @SuppressWarnings("rawtypes") + List list = root.selectNodes("action[@name='" + attr + "']/result[@name='" + result + "']"); + + String jsp = null; + for (Object o : list) { + Element e = (Element) o; + jsp = e.getTextTrim(); + } + return jsp; + } + +} diff --git a/group12/382266293/coding/basic/util/Print.java b/group12/382266293/coding/basic/util/Print.java new file mode 100644 index 0000000000..db18c2a019 --- /dev/null +++ b/group12/382266293/coding/basic/util/Print.java @@ -0,0 +1,19 @@ +package util; + +import java.util.Arrays; + +public class Print { + + public static void print(Object o) { + System.out.print(o); + } + + public static void println(Object o) { + System.out.println(o); + } + + public static void printArr(Object[] arr) { + println(Arrays.toString(arr)); + } + +} diff --git a/group12/382266293/src/util/TestUtil.java b/group12/382266293/coding/basic/util/TestUtil.java similarity index 59% rename from group12/382266293/src/util/TestUtil.java rename to group12/382266293/coding/basic/util/TestUtil.java index 2dfeeade7f..3b607378b5 100644 --- a/group12/382266293/src/util/TestUtil.java +++ b/group12/382266293/coding/basic/util/TestUtil.java @@ -2,36 +2,46 @@ import java.util.Random; -import Collection.List; -import Collection.Concrete.ArrayList; -import Collection.Concrete.LinkedList; -import Collection.Concrete.Queue; +import collection.List; +import collection.concrete.ArrayList; +import collection.concrete.LinkedList; +import collection.concrete.Queue; import junit.framework.TestCase; - public class TestUtil extends TestCase { - + private static Random random = new Random(); - private static final int RANDOM_BOUND = 2<<15; + private static final int RANDOM_BOUND = 2 << 15; private static final int RANDOM_SIZE = 500; - - + + public static int[] getRandomIntArray(int number) { + int[] arr = new int[number]; + for (int i = 0; i < arr.length; i++) { + arr[i] = getRandomNumber() + 1; + } + return arr; + } + public static int getRandomNumber() { return random.nextInt(RANDOM_SIZE); } - + + public static int getRandomNumber(int bound) { + return random.nextInt(bound); + } + public static void addIntWithNatureOrder(List myList, int numbers) { - - for (int acutal = 0; acutal < numbers ; acutal++) { + + for (int acutal = 0; acutal < numbers; acutal++) { myList.add(acutal); } } - + public static int[] addRandomInt(List myList, int numbers) { - + int actual = 0; int[] result = new int[numbers]; - for (int i = 0; i < numbers ; i++) { + for (int i = 0; i < numbers; i++) { actual = random.nextInt(RANDOM_BOUND); result[i] = actual; myList.add(actual); @@ -40,39 +50,39 @@ public static int[] addRandomInt(List myList, int numbers) { } public static void addString(List myList, int num) { - + String actual; - for (int index = 0; index < num ; index++) { + for (int index = 0; index < num; index++) { actual = index + ""; myList.add(actual); } } - + public static void testRemoveAndGetFromTail(ArrayList myList) { E get; E remove; - for(int i = myList.size()-1; i >= 0; i--) { + for (int i = myList.size() - 1; i >= 0; i--) { get = myList.get(i); remove = myList.remove(i); - assertEquals(get,remove); + assertEquals(get, remove); } } - + public static void testRemoveAndGetFromTail(LinkedList myList) { E get; E remove; - for(int i = myList.size()-1; i >= 0; i--) { + for (int i = myList.size() - 1; i >= 0; i--) { get = myList.get(i); remove = myList.remove(i); - assertEquals(get,remove); + assertEquals(get, remove); } } public static void enQueueIntWithNatureOrder(Queue myQueue, int numbers) { - - for (int acutal = 0; acutal < numbers ; acutal++) { + + for (int acutal = 0; acutal < numbers; acutal++) { myQueue.enQueue(acutal); } } - + } diff --git a/group12/382266293/lib/.gitignore b/group12/382266293/lib/.gitignore new file mode 100644 index 0000000000..edf7850106 --- /dev/null +++ b/group12/382266293/lib/.gitignore @@ -0,0 +1,3 @@ +/dom4j-1.6.1.zip +/jaxen-1.1-beta-6.jar +/dom4j-1.6.1.jar diff --git a/group12/382266293/src/Collection/Concrete/LinkedList.java b/group12/382266293/src/Collection/Concrete/LinkedList.java deleted file mode 100644 index 66dbd9d8d0..0000000000 --- a/group12/382266293/src/Collection/Concrete/LinkedList.java +++ /dev/null @@ -1,196 +0,0 @@ -package Collection.Concrete; - -import java.util.NoSuchElementException; -import Collection.AbstractList; -import Collection.Iterator; - - -public class LinkedList extends AbstractList { - - private Node head; - private int size; - - public LinkedList() { - this.head = new Node(null); - this.size = 0; - } - - @Override - public void add(E e) { - addLast(e); - } - - - @Override - public E get(int index) { - checkIndex(index); - return getNode(index).data; - } - - public E getFirst() { - return get(0); - } - - public E getLast() { - return get(size-1); - } - - - public void add(int index, E e) { - if (index == size) { - addLast(e); - return; - } - - if (index == 0) { - addFirst(e); - return; - } - - checkIndex(index); - Node pNode = new Node(e); - Node p = getNode(index); - synchronized (this) { - getNode(index-1).next = pNode; - pNode.next = p; - size++; - } - } - - public void addFirst(E e){ - checkCapacity(); - Node pNode = new Node(e); - Node oldHead = head; - head = pNode; - pNode.next = oldHead; - size++; - return; - } - - public void addLast(E e){ - if (size == 0) { - addFirst(e); - return; - } - - checkCapacity(); - Node res = new Node(e); - setLastNode(res); - size++; - return; - } - - public E removeFirst(){ - return remove(0); - } - public E removeLast(){ - return remove(size-1); - } - - public E remove(int index) { - checkIndex(index); - Node pNode = getNode(index); - if (index == 0) { - head = head.next; - } else if (index == size-1 ) { - getNode(index-1).next = null; - } else { - getNode(index-1).next = getNode(index+1); - } - size--; - return pNode.data; - } - - @Override - public int size() { - return size; - } - - public Iterator iterator(){ - return new LinkedListIterator(this); - } - - private void checkCapacity() { - if (size > MAX_SIZE) - throw new IndexOutOfBoundsException("Reached max capacity: "+ MAX_SIZE); - } - - private Node getNode(int index) { - if (size == 0) - return head; - - Node pNode = head; - for ( int i = 0; i < index ; i++) { - pNode = pNode.next; - } - return pNode; - } - - private void setLastNode(Node res) { - getNode(size-1).next = res; - } - - private static class Node { - E data; - Node next; - - public Node(E data) { - this.data = data; - this.next = null; - } - - @Override - public String toString() { - return data.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Node other = (Node) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - return true; - } - } - - @SuppressWarnings("hiding") - private class LinkedListIterator implements Iterator { - - private LinkedList myLinkedList; - private int pos; - - public LinkedListIterator(LinkedList linkedList) { - myLinkedList = linkedList; - pos = 0; - } - - @Override - public boolean hasNext() { - return pos < size; - } - - @Override - public E next() { - if (hasNext()) - return (E) get(pos++); - throw new NoSuchElementException(); - } - } -} diff --git a/group12/382266293/src/array/ArrayUtil.java b/group12/382266293/src/array/ArrayUtil.java new file mode 100644 index 0000000000..8412a68f48 --- /dev/null +++ b/group12/382266293/src/array/ArrayUtil.java @@ -0,0 +1,235 @@ +package array; + +import java.util.Arrays; +import java.util.BitSet; + +import collection.Iterator; +import collection.concrete.ArrayList; + + + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + int temp; + int index = origin.length - 1; + int numbersToReverse = origin.length/2; + for (int i = 0; i < numbersToReverse ; i++) { + temp = origin[i]; + origin[i] = origin[index - i]; + origin[index - i] = temp; + } + } + + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + + BitSet check = new BitSet(oldArray.length); + boolean isZero; + for (int i = 0; i < oldArray.length; i++) { + isZero = (oldArray[i] == 0) ? true : false; + check.set(i, isZero); + } + + int newSize = oldArray.length-check.cardinality(); + int[] newArr = new int[newSize]; + + int nextIndex = check.nextClearBit(0); + for(int i = 0 ; i < newSize ; i++) { + newArr[i] = oldArray[nextIndex]; + nextIndex = check.nextClearBit(nextIndex+1); + } + + return newArr; + } + + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + + int len1 = array1.length; + int len2 = array2.length; + int len3 = array1[len1-1] < array2[len2-1] ? array2[len2-1] + 1: array1[len1-1] + 1; + int[] newArr = new int[len3]; + initialArray(newArr, -1); + for (int i = 0; i < len1; i++) { + newArr[array1[i]] = 0; + } + for (int i = 0; i < len2; i++) { + newArr[array2[i]] = 0; + } + int mergedLength = 0; + for (int i = 0; i < len3; i++) { + if (newArr[i] != -1) + newArr[mergedLength++] = i; + } + return Arrays.copyOf(newArr, mergedLength); + } + + public static void initialArray(int[] arr, int j) { + for (int i = 0; i < arr.length; i++) { + arr[i] = j; + } + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + + int[] newArr = new int[oldArray.length + size]; + for (int i = 0; i < oldArray.length; i++) { + newArr[i] = oldArray[i]; + } + return newArr; + } + + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + if (max == 1) + return new int[0]; + int[] result = new int[max]; + result[0] = result[1] = 1; + int count = 0; + for (int i = 2, j = 0; j < max ; i++) { + result[i] = result[i-1] + result[i-2]; + j = result[i]; + count++; + } + return Arrays.copyOf(result, ++count); + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + + String temp = ""; + for(int i = 0; i < max; i++) { + if(isPrime(i)) { + temp += i + " "; + } + } + String[] tempArr = temp.split(" "); + int[] result = new int[tempArr.length]; + for (int i = 0; i < result.length; i++) { + result[i] = Integer.parseInt(tempArr[i]); + } + + return result; + } + + public static boolean isPrime(int num) { + + if (num <= 1) + return false; + + if (num == 2) + return true; + + for(int i = 2; i <= Math.sqrt(num) + 1; i++) { + if (num % i == 0) + return false; + } + + return true; + } + + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + + int count = 0; + ArrayList myList = new ArrayList(); + for(int i = 1; i < max; i++) { + if(isPerfectNum(i)) { + count++; + myList.add(i); + } + } + int[] result = new int[count]; + Iterator iterator = myList.iterator(); + for (int i = 0; i < count; i++) { + result[i] = iterator.next(); + } + return result; + } + + + public static boolean isPerfectNum(int num) { + + int sum = 0; + for (int i = 1; i <= num/2; i++) { + if (num % i == 0) + sum += i; + } + + return (num == sum) ? true : false; + + } + + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + sb.append(array[i]); + if (i < array.length-1) + sb.append(seperator); + } + return sb.toString(); + } + + +} \ No newline at end of file diff --git a/group12/382266293/src/array/ArrayUtilTest.java b/group12/382266293/src/array/ArrayUtilTest.java new file mode 100644 index 0000000000..42085c1e25 --- /dev/null +++ b/group12/382266293/src/array/ArrayUtilTest.java @@ -0,0 +1,158 @@ +package array; + +import static org.junit.Assert.*; +import static util.TestUtil.*; +import java.util.Arrays; +import java.util.Iterator; +import java.util.TreeSet; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + + + +public class ArrayUtilTest { + + private int[] actual; + ArrayUtil au = new ArrayUtil(); + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + actual = null; + } + + + @Test + public void testReverseArray() { + + int size = getRandomNumber(); + int[] expected = getRandomIntArray(size); + actual = Arrays.copyOf(expected, size); + + au.reverseArray(actual); + + for (int i = 0; i < size; i++) { + assertEquals(expected[i], actual[size-1-i]); + } + + } + + @Test + public void testRemoveZero() { + + int size = getRandomNumber(10000); + int[] expected = getRandomIntArray(size); + + int zeros = getRandomNumber(size-1); + TreeSet t = new TreeSet(); + while (t.size() != zeros) { + t.add(getRandomNumber(size)); + } + + for (Integer i : t) { + expected[i] = 0; + } + + int expectedSize = size - zeros; + actual = au.removeZero(expected); + assertEquals(expectedSize, actual.length); + + for (int i = 0, j = 0; i < size; i++) { + if (expected[i] != 0) + assertEquals(expected[i], actual[j++]); + } + + } + + @Test + public void testMerge() { + int[] arr1 = getRandomIntArray(getRandomNumber()); + int[] arr2 = getRandomIntArray(getRandomNumber()); + Arrays.sort(arr1); + Arrays.sort(arr2); + TreeSet t = new TreeSet(); + for (int i = 0; i < arr1.length; i++) { + t.add(arr1[i]); + } + for (int i = 0; i < arr2.length; i++) { + t.add(arr2[i]); + } + int[] actual = new int[arr1.length + arr2.length]; + actual = au.merge(arr1, arr2); + + assertEquals(t.size(), actual.length); + + Iterator it = t.iterator(); + for(int i = 0; it.hasNext(); i++) { + assertEquals((int)it.next(), actual[i]); + } + + } + + @Test + public void testGrow() { + int[] expected = getRandomIntArray(getRandomNumber()); + int growSize = getRandomNumber(); + int[] actual = au.grow(expected, growSize); + + assertEquals(expected.length + growSize, actual.length); + + for (int i = 0; i < actual.length; i++) { + if (i < expected.length) { + assertEquals(expected[i], actual[i]); + } else { + assertEquals(0, actual[i]); + } + } + + } + + @Test + public void testFibonacci() { + int[] expected = new int[] {1, 1, 2, 3, 5, 8, 13}; + int[] acutal = new int[expected.length]; + actual = au.fibonacci(15); + assertArrayEquals(expected,actual); + } + + @Test + public void testGetPrimes() { + + int[] expected = new int[] {2,3,5,7,11,13,17,19}; + int[] acutal = new int[expected.length]; + actual = au.getPrimes(23); + assertArrayEquals(expected,actual); + } + + @Test + public void testGetPerfectNumbers() { + + int[] expected = new int[] {6, 28, 496, 8128}; + int[] acutal = new int[expected.length]; + actual = au.getPerfectNumbers(10000); + assertArrayEquals(expected,actual); + } + + @Test + public void testJoin() { + + int[] expected = getRandomIntArray(getRandomNumber()); + String seperator = "-"; + String joinedString = au.join(expected, seperator); + + String[] actual = joinedString.split(seperator); + + assertEquals(expected.length, actual.length); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], Integer.parseInt(actual[i])); + } + + } + +} diff --git a/group12/382266293/src/com/coderising/action/LoginAction.java b/group12/382266293/src/com/coderising/action/LoginAction.java new file mode 100644 index 0000000000..b1224eb80d --- /dev/null +++ b/group12/382266293/src/com/coderising/action/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.action; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} \ No newline at end of file diff --git a/group12/382266293/src/com/coderising/download/DownloadThread.java b/group12/382266293/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..d1e1f04c47 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,70 @@ +package com.coderising.download; + +import java.io.File; +import java.io.IOException; + +import java.io.RandomAccessFile; + +import com.coderising.download.api.Connection; + + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + private String dest; + private FileDownloader fileDownloader; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + @Override + public void run(){ + System.out.println(this.getName()+" is running"); + RandomAccessFile raf = null; + try { + byte[] buffer = conn.read(startPos, endPos); + raf = new RandomAccessFile(new File(dest), "rws"); + raf.seek(startPos); + raf.write(buffer); + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + conn.close(); + System.out.println(this.getName()+" finished"); + + try { + if (raf != null) + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + notifyFinished(); + } + } + } + + public void setFileDownloader(FileDownloader fileDownloader) { + this.fileDownloader = fileDownloader; + } + + public void notifyFinished() { + fileDownloader.setThreadFinished(); + } + + public void setDest(String dest) { + this.dest = dest; + } + + public void close() { + this.conn.close(); + + } + + +} diff --git a/group12/382266293/src/com/coderising/download/DownloadUtil.java b/group12/382266293/src/com/coderising/download/DownloadUtil.java new file mode 100644 index 0000000000..8e8f2de727 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/DownloadUtil.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public class DownloadUtil { + + private static final int MIN_CONNECTIONS = 3; + private static final int MAX_CONNECTIONS = 10; + + public static long getCurrentTime() { + return System.currentTimeMillis(); + } + + public static void createTempFile(String tempName, int len) { + File file = new File(tempName); + if (file.exists()) { + System.out.println("tempfile already created"); + return; + } + FileOutputStream temp = null; + try { + temp = new FileOutputStream(tempName); + int length = len; + byte[] buffer = new byte[1024]; + long times = length / 1024; + int left = length % 1024; + for (int i = 0; i < times; i++) { + temp.write(buffer); + } + temp.write(buffer, 0, left); + System.out.println("tempFile " + tempName + " created"); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + temp.flush(); + temp.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static int calculateConnects(int length) { + int conns = length / 1024 / 1024 / 25; + if (conns < MIN_CONNECTIONS) { + return MIN_CONNECTIONS; + } else if (conns > MAX_CONNECTIONS) { + return MAX_CONNECTIONS; + } else { + return conns; + } + } + + public static boolean rename(String from, String to) { + File file = new File(from); + if (file.exists()) { + return file.renameTo(new File(to)); + } + System.out.println("rename failed"); + return false; + } + + public static void printDownloadReport(int length, long start, long end) { + int time = (int) ((end - start) / 1000); + float speed = (float)length / 1024 / 1024 / time; + System.out.println("共耗时:" + time + "s,下载速度: " + (float)(Math.round(speed*100))/100 + "Mb/s"); + } + +} \ No newline at end of file diff --git a/group12/382266293/src/com/coderising/download/FileDownloader.java b/group12/382266293/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..cc77b380a9 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,175 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + +public class FileDownloader { + + private final static String EXT = "lyj"; + private static DownloadThread[] threadPool; + private int finishedCount; + public String downloadLocation; + + String url; + ConnectionManager cm; + DownloadListener listener; + private static String fileName; + private static String tempName; + + public FileDownloader(String _url) { + this.url = _url; + this.finishedCount = 0; + } + + public void execute() { + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, + // endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, + // 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + + long start = getCurrentTime(); + try { + Connection conn = cm.open(this.url); + int length = conn.getContentLength(); + checkLength(length, conn); + + System.out.println("file length:" + length); + setLocation("C:\\"); + + String name = conn.getFileName(); + setFileName(name); + setTempName(name); + + DownloadUtil.createTempFile(tempName, length); + + int connNumbers = DownloadUtil.calculateConnects(length); + System.out.println(connNumbers + " Threads will be created."); + + threadPool = new DownloadThread[connNumbers]; + setAndStartThreadPool(conn, threadPool, length); + + checkFinish(threadPool.length); + + listener.notifyFinished(); + DownloadUtil.rename(tempName, fileName); + long end = getCurrentTime(); + DownloadUtil.printDownloadReport(length, start, end); + + } catch (ConnectionException e) { + e.printStackTrace(); + } finally { + freeDownloadThread(); + } + } + + private void checkLength(int length, Connection conn) { + if (length <= 0) { + try { + throw new ConnectionException("file does not exist"); + } catch (ConnectionException e) { + e.printStackTrace(); + } finally { + conn.close(); + } + } + } + + private void setTempName(String name) { + String temp = name.substring(0, name.lastIndexOf(".") + 1) + EXT; + FileDownloader.tempName = downloadLocation + temp; + } + + private void setFileName(String name) { + FileDownloader.fileName = downloadLocation + name; + } + + private void setLocation(String downloadLocation) { + this.downloadLocation = downloadLocation; + } + + private boolean checkFinish(int links) { + + while (finishedCount != links) { + try { + Thread.sleep(5000); + System.out.println("Unfinshed threads number: " + (links - finishedCount)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return true; + } + + private void freeDownloadThread() { + if (threadPool != null) { + for (int i = 0; i < threadPool.length; i++) { + if (threadPool[i] != null) + threadPool[i].close(); + } + } + } + + private long getCurrentTime() { + return System.currentTimeMillis(); + } + + public String getDownloadLocation() { + return downloadLocation; + } + + public DownloadListener getListener() { + return this.listener; + } + + private void setAndStartThreadPool(Connection conn, DownloadThread[] threadPool, int length) + throws ConnectionException { + int connectionNumbers = threadPool.length; + int batch_size = length / connectionNumbers; + int beginPos = 0; + int endPos = batch_size; + threadPool[0] = new DownloadThread(conn, beginPos, endPos); + setAndStartThread(threadPool[0], tempName); + for (int i = 1; i < connectionNumbers; i++) { + Connection con = cm.open(this.url); + beginPos = endPos + 1; + endPos = beginPos + batch_size; + if (i == connectionNumbers - 1) { + endPos = length - 1; + } + threadPool[i] = new DownloadThread(con, beginPos, endPos); + setAndStartThread(threadPool[i], tempName); + } + } + + private void setAndStartThread(DownloadThread downloadThread, String dest) { + downloadThread.setDest(dest); + downloadThread.setFileDownloader(this); + downloadThread.start(); + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public void setThreadFinished() { + finishedCount++; + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + +} diff --git a/group12/382266293/src/com/coderising/download/FileDownloaderTest.java b/group12/382266293/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..ae24faa19f --- /dev/null +++ b/group12/382266293/src/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,61 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + public static String qq = "http://sw.bos.baidu.com/sw-search-sp/software/89179b0b248b1/QQ_8.9.20026.0_setup.exe"; + public static String picture = "http://image.beekka.com/blog/201304/bg2013042401.jpg"; + public static String foxmail = "http://sw.bos.baidu.com/sw-search-sp/software/6c7bb8b6674d0/fm728chb379_7.2.8.379_setup.exe"; + + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(foxmail); + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + // 休眠5秒 + Thread.sleep(15000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + } + +} diff --git a/group12/382266293/src/com/coderising/download/api/Connection.java b/group12/382266293/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..63d9fc7b19 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/api/Connection.java @@ -0,0 +1,27 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + + public void close(); + public String getFileName(); + public void setFinished(); + public boolean isFinished(); +} diff --git a/group12/382266293/src/com/coderising/download/api/ConnectionException.java b/group12/382266293/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..b073bf2d6d --- /dev/null +++ b/group12/382266293/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,9 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + + public ConnectionException(String string) { + super(string); + } + +} diff --git a/group12/382266293/src/com/coderising/download/api/ConnectionManager.java b/group12/382266293/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..17f1e544b1 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,13 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + + final int MAX_CONNECTION_SIZE = 100; + + public Connection open(String url) throws ConnectionException; +} diff --git a/group12/382266293/src/com/coderising/download/api/DownloadListener.java b/group12/382266293/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..4cd0b3eab1 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group12/382266293/src/com/coderising/download/impl/ConnectionImpl.java b/group12/382266293/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..05f31103de --- /dev/null +++ b/group12/382266293/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,84 @@ +package com.coderising.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionManager; + +import sun.net.www.protocol.http.HttpURLConnection; + +public class ConnectionImpl implements Connection{ + + private ConnectionManager cm; + private static int buffer_size = 1024; + private HttpURLConnection httpConn; + private URL url; + private boolean finished = false; + + public ConnectionImpl(ConnectionManager cm, String _url) { + this.cm = cm; + try { + url = new URL(_url); + httpConn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + InputStream in = null; + ByteArrayOutputStream out = null; + try { + in = httpConn.getInputStream(); + out = new ByteArrayOutputStream(); + in = httpConn.getInputStream(); + in.skip(startPos); + byte[] buffer = new byte[endPos-startPos + 1]; + int len = 0; + byte[] b = new byte[1024]; + while((len = in.read(b)) != -1) { + out.write(b, 0, len); + } + return out.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public int getContentLength() { + int len = httpConn.getContentLength(); + + return len; + + } + + @Override + public void close() { + httpConn.disconnect(); + } + + @Override + public String getFileName() { + String fileName = httpConn.getURL().getFile(); + fileName = fileName.substring(fileName.lastIndexOf('/')+1); + return fileName; + } + + @Override + public void setFinished() { + finished = true; + } + + @Override + public boolean isFinished() { + return finished; + } + + +} diff --git a/group12/382266293/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group12/382266293/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..4d44301b0d --- /dev/null +++ b/group12/382266293/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,46 @@ +package com.coderising.download.impl; + +import java.io.IOException; +import java.net.URL; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + private int connections = 0; + private String url; + + public ConnectionManagerImpl() { + this.connections = 0; + } + + @Override + public Connection open(String url) throws ConnectionException { + this.url = url; + checkConnectionSize(); + URL address = null; + Connection conn = null; + try { + address = new URL(url); + conn = new ConnectionImpl(this,url); + connections++; + return conn; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + private void checkConnectionSize() { + if (connections > MAX_CONNECTION_SIZE) + try { + throw new NoFreeSourceException("No free connections available."); + } catch (NoFreeSourceException e) { + e.printStackTrace(); + } + } + +} + diff --git a/group12/382266293/src/com/coderising/download/impl/DownloadUtil.java b/group12/382266293/src/com/coderising/download/impl/DownloadUtil.java new file mode 100644 index 0000000000..834a68d702 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/impl/DownloadUtil.java @@ -0,0 +1,44 @@ +package com.coderising.download.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public class DownloadUtil { + + public static long getCurrentTime() { + return System.currentTimeMillis(); + } + + public static void createTempFile(String tempName, int len) { + File file = new File(tempName); + if (file.exists()) { + System.out.println("tempfile already created"); + return; + } + FileOutputStream temp = null; + try { + temp = new FileOutputStream(tempName); + int length = len; + byte[] buffer = new byte[1024]; + long times = length / 1024; + int left = length % 1024; + for (int i = 0; i < times; i++) { + temp.write(buffer); + } + temp.write(buffer, 0, left); + System.out.println("tempFile " + tempName + " created"); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + temp.flush(); + temp.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/group12/382266293/src/com/coderising/download/impl/NoFreeSourceException.java b/group12/382266293/src/com/coderising/download/impl/NoFreeSourceException.java new file mode 100644 index 0000000000..f2f68c3aa0 --- /dev/null +++ b/group12/382266293/src/com/coderising/download/impl/NoFreeSourceException.java @@ -0,0 +1,10 @@ +package com.coderising.download.impl; + +public class NoFreeSourceException extends Exception { + + + public NoFreeSourceException(String string) { + super(string); + } + +} diff --git a/group12/382266293/src/litestruts/ActionXMLreader.java b/group12/382266293/src/litestruts/ActionXMLreader.java new file mode 100644 index 0000000000..92e700edc4 --- /dev/null +++ b/group12/382266293/src/litestruts/ActionXMLreader.java @@ -0,0 +1,50 @@ +package litestruts; + +import java.util.List; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.Node; +import org.dom4j.io.SAXReader; + +public class ActionXMLreader { + + public Node getRootNode(String add) { + SAXReader reader = new SAXReader(); + Document document = null; + Node root = null; + try { + document = reader.read(add); + root = document.getRootElement(); + } catch (DocumentException e) { + e.printStackTrace(); + } + return root; + } + + public String parseClass(Node root, String attr) { + + @SuppressWarnings("rawtypes") + List list = root.selectNodes("action[@name='" + attr + "']"); + String clazz = null; + for (Object o : list) { + Element e = (Element) o; + clazz = e.attributeValue("class"); + } + return clazz; + } + + public String parseResult(Node root, String attr, String result) { + + @SuppressWarnings("rawtypes") + List list = root.selectNodes("action[@name='" + attr + "']/result[@name='" + result + "']"); + + String jsp = null; + for (Object o : list) { + Element e = (Element) o; + jsp = e.getTextTrim(); + } + return jsp; + } + +} diff --git a/group12/382266293/src/litestruts/Configuration.java b/group12/382266293/src/litestruts/Configuration.java new file mode 100644 index 0000000000..9b7d4e8466 --- /dev/null +++ b/group12/382266293/src/litestruts/Configuration.java @@ -0,0 +1,104 @@ +package litestruts; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.input.SAXBuilder; +import static util.Print.*; +public class Configuration { + + + ActionCfg actionCfg = new ActionCfg(); + + private static Configuration cfg = new Configuration(); + + private Configuration() { + + } + + public static Configuration getNewInstance() { + + if (cfg == null) { + cfg = new Configuration(); + } + return cfg; + } + + private String getFile(String fileName) { + + String src = this.getClass().getPackage().getName(); + return "file://" + src + "\\" + fileName + ".xml"; + } + + public void parseAction(String src) { + + String fileName = getFile(src); + SAXBuilder reader = new SAXBuilder(); + try { + Document doc = reader.build("C:\\struts.xml"); + Element root = doc.getRootElement(); + + for(Element element : root.getChildren("action")) { + + String name = element.getAttributeValue("name"); + String clz = element.getAttributeValue("class"); + actionCfg.actionInfo.put(name, clz); + + for(Element e : element.getChildren("result")) { + + String result = e.getAttributeValue("name"); + String jsp = e.getText().trim(); + println("result:" + result + "jsp:" + jsp); + Map res = new HashMap<>(); + res.put(result, jsp); + actionCfg.resultInfo.put(name, res); + } + } + + } catch (JDOMException | IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + Configuration cfg = new Configuration(); + cfg.parseAction("struts"); + Map info = cfg.getActionInfo(); + Map result = cfg.getResultInfo().get("login"); + println(info); + println(result); + } + + + private static class ActionCfg { + + private Map actionInfo; + private Map> resultInfo; + public ActionCfg() { + this.actionInfo = new HashMap(); + this.resultInfo = new HashMap>(); + } + + } + + + public Map> getResultInfo() { + + return actionCfg.resultInfo; + } + + public Map getActionInfo() { + + return actionCfg.actionInfo; + } + + + + + +} diff --git a/group12/382266293/src/litestruts/ConfigurationTest.java b/group12/382266293/src/litestruts/ConfigurationTest.java new file mode 100644 index 0000000000..1b5d2f43e1 --- /dev/null +++ b/group12/382266293/src/litestruts/ConfigurationTest.java @@ -0,0 +1,33 @@ +package litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ConfigurationTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetGetterMethods() { + Configuration cfg = Configuration.getNewInstance(); + Map actionName = new HashMap<>(); + actionName.put("login","com.coderising.action.LoginAction"); + actionName.put("logout","com.coderising.action.LogoutAction"); + + //Assert.assertTrue(cfg.getActionName().containsKey(actionName)); + + + + } + +} diff --git a/group12/382266293/src/litestruts/Struts.java b/group12/382266293/src/litestruts/Struts.java new file mode 100644 index 0000000000..df9c4ed535 --- /dev/null +++ b/group12/382266293/src/litestruts/Struts.java @@ -0,0 +1,115 @@ +package litestruts; + +import util.ActionXMLreader; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; +import org.dom4j.Node; + +public class Struts { + + private static Object actionObj = null; + private static String address = "src/litestruts/struts.xml"; + private static ActionXMLreader reader = new ActionXMLreader(); + + @SuppressWarnings("unchecked") + public static View runAction(String actionName, Map parameters){ + + Node root = reader.getRootNode(address); + String clazz = reader.parseClass(root, actionName); + actionObj = getObj(clazz); + BeanInfo bi = getBeanInfo(actionObj); + PropertyDescriptor[] pd = bi.getPropertyDescriptors(); + + setParameters(actionObj, pd, parameters); + String executeResult = getResult(actionObj, bi, "execute"); + String jsp = reader.parseResult(root, actionName, executeResult); + Map readParamters = getReadParameters(actionObj, pd); + + View view = new View(); + view.setJsp(jsp); + view.setParameters(readParamters); + + return view; + } + + + private static Object getObj(String clazz) { + @SuppressWarnings("rawtypes") + Class cls = null; + + try { + cls = Class.forName(clazz); + return cls.newInstance(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + }catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + + private static BeanInfo getBeanInfo(Object obj) { + + BeanInfo bi = null; + try { + bi = Introspector.getBeanInfo(obj.getClass(), Object.class); + } catch (IntrospectionException e) { + e.printStackTrace(); + } + return bi; + } + + private static void setParameters(Object obj, PropertyDescriptor[] pd ,Map parameters) { + + for (int i = 0; i < pd.length; i++) { + String name = pd[i].getName(); + if(parameters.containsKey(name)) + try { + pd[i].getWriteMethod().invoke(obj,parameters.get(name)); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + + private static String getResult(Object obj, BeanInfo bi,String execute) { + MethodDescriptor[] methods = bi.getMethodDescriptors(); + for (int i = 0; i < methods.length; i++) { + String methodName = methods[i].getName(); + if(methodName.equals(execute)) + try { + return (String) methods[i].getMethod().invoke(actionObj); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + return null; + } + + @SuppressWarnings("rawtypes") + public static Map getReadParameters (Object obj, PropertyDescriptor[] pd) { + + Map viewParams = new HashMap(); + + for (int i = 0; i < pd.length; i++) { + String readMethod = pd[i].getReadMethod().getName().substring(3); + String value = null; + try { + value = (String) pd[i].getReadMethod().invoke(obj); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + viewParams.put(readMethod.toLowerCase(), value); + } + return viewParams; + } + + +} \ No newline at end of file diff --git a/group12/382266293/src/litestruts/StrutsTest.java b/group12/382266293/src/litestruts/StrutsTest.java new file mode 100644 index 0000000000..35686c8e30 --- /dev/null +++ b/group12/382266293/src/litestruts/StrutsTest.java @@ -0,0 +1,41 @@ +package litestruts; + +import java.beans.IntrospectionException; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} \ No newline at end of file diff --git a/group12/382266293/src/litestruts/View.java b/group12/382266293/src/litestruts/View.java new file mode 100644 index 0000000000..5a7d948765 --- /dev/null +++ b/group12/382266293/src/litestruts/View.java @@ -0,0 +1,23 @@ +package litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} \ No newline at end of file diff --git a/group12/382266293/src/litestruts/struts.xml b/group12/382266293/src/litestruts/struts.xml new file mode 100644 index 0000000000..fb0c2be3de --- /dev/null +++ b/group12/382266293/src/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/382266293/src/test.java b/group12/382266293/src/test.java index e4e7fead2d..a705772df2 100644 --- a/group12/382266293/src/test.java +++ b/group12/382266293/src/test.java @@ -1,14 +1,117 @@ -import java.util.ArrayList; -import java.util.Queue; -import java.util.Stack; -import java.util.concurrent.PriorityBlockingQueue; -import static util.Print.*; +import static util.Print.println; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; +import sun.net.www.protocol.http.HttpURLConnection; public class test { - public static void main(String[] args) { - Queue queue = new PriorityBlockingQueue(); - println(queue.poll()); + public static String url = "http://sw.bos.baidu.com/sw-search-sp/software/89179b0b248b1/QQ_8.9.20026.0_setup.exe"; + public static String url2 = "http://image.beekka.com/blog/201304/bg2013042401.jpg"; + public static String downloadLocation = "C:\\"; + public static String tempName = ""; + public static String fileName = ""; + + LinkedList a; + + private static void createTempFile1(String from) { + long length = 0; + URL url = null; + HttpURLConnection conn = null; + try { + url = new URL(from); + conn = (HttpURLConnection)url.openConnection(); + String file = conn.getURL().getFile(); + fileName = file.substring(file.lastIndexOf('/')+1); + tempName = fileName.substring(0, fileName.lastIndexOf('.')+1) + "lyj"; + length = conn.getContentLength(); + conn.disconnect(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + conn.disconnect(); + } + tempName = downloadLocation + tempName; + fileName = downloadLocation + fileName; + bufferFile(tempName,length); + } + + public static void bufferFile(String name, long len) { + + FileOutputStream temp = null; + try { + temp = new FileOutputStream(name); + long length = len; + byte[] buffer = new byte[1024]; + long times = length / 1024; + int left = (int) (length % 1024); + for (int i = 0; i < times; i++) { + temp.write(buffer); + } + temp.write(buffer, 0, left); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + temp.flush(); + temp.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + + public static void download(String src) { + createTempFile1(src); + + URL url = null; + HttpURLConnection conn = null; + FileOutputStream out = null; + InputStream in = null; + try { + url = new URL(src); + conn = (HttpURLConnection)url.openConnection(); + in = conn.getInputStream(); + out = new FileOutputStream(tempName); + byte[] buffer = new byte[1024]; + int len = 0; + while( (len = in.read(buffer)) != -1) { + out.write(buffer, 0, len); + } + conn.disconnect(); + println(fileName); + println(rename(tempName)); + println("Download Complete!"); + } catch (IOException e) { + e.printStackTrace(); + } finally { + conn.disconnect(); + } + + } + + public static boolean rename(String temp) { + File file=new File(temp); + File f1=new File(fileName); + if( file.exists() ) { + file.renameTo(f1); + file = f1; + System.out.println("文件重命名为:"+f1.getName()); + return true; + } + return false; + } + + + public static void main(String[] args) throws IOException { + + download(url2); } diff --git a/group12/382266293/src/util/Print.java b/group12/382266293/src/util/Print.java deleted file mode 100644 index b2ae48552b..0000000000 --- a/group12/382266293/src/util/Print.java +++ /dev/null @@ -1,14 +0,0 @@ -package util; - - -public class Print { - - public static void print(Object o){ - System.out.print(o); - } - - public static void println(Object o){ - System.out.println(o); - } - -} diff --git a/group12/446031103/src/com/coderising/array/ArrayUtil.java b/group12/446031103/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..a771999a22 --- /dev/null +++ b/group12/446031103/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,202 @@ +package com.coderising.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + int end = origin.length-1; + int temp ; + for (int i = 0; i < end; i++,end--) { + temp=origin[i]; + origin[i]=origin[end]; + origin[end] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + int zeroCnt = 0; + for (int i : oldArray) { + if(0==i){ + zeroCnt++; + } + + } + int size = 0; + int [] result = new int[oldArray.length-zeroCnt]; + for (int i : oldArray) { + if(0!=i){ + result[size]=i; + size++; + } + + } + return result; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + //合拼数组,缺排序,缺去重 + int [] temp = new int[array1.length+array2.length]; + System.arraycopy(array1, 0, temp, 0, array1.length); + System.arraycopy(array2, 0, temp, array1.length, array2.length); + List resultList= new ArrayList(); + for (int i : temp) { + if(!resultList.contains(i)) + resultList.add(i); + }//已去重数组,缺排序 + int [] result = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + result[i] = resultList.get(i); + } + //冒泡排序 + for (int i = 0; i < result.length-1; i++) { + for (int j = 0; j < result.length-i-1; j++) { + if(result[j]>result[j+1]){ + int tempInt = result[j]; + result[j] =result[j+1]; + result[j+1] = tempInt; + } + } + + } + return result; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return Arrays.copyOf(oldArray, oldArray.length+size); + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + int first =0; + int second = 1; + List resultList= new ArrayList(); + if(max!=second) + add(first,second,max,resultList); + int [] result = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + result[i] = resultList.get(i); + } + return result; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + List resultList= new ArrayList(); + for (int i = 2; i < max; i++) { + boolean isAdd = true; + for (int j = 2; j < i; j++) { + if(0==i%j){ + isAdd = false; + break; + } + } + if(isAdd) + resultList.add(i); + } + int [] result = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + result[i] = resultList.get(i); + } + return result; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + List resultList= new ArrayList(); + for (int i = 1; i < max; i++) { + int temp = 0; + for (int j = 1; j < i; j++) { + if(0==i%j){ + temp+=j; + } + } + if(i==temp) + resultList.add(i); + } + int [] result = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + result[i] = resultList.get(i); + } + return result; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return Arrays.toString(array).replace("[", "").replace("]", "").replace(", ", seperator); + } + + /** + * + * @param number1 + * @param number2 + * @param max + * @param resultList + * @return + */ + public List add(int number1,int number2,int max,List resultList){ + if(number2 parameters) { + Map xmlDoc = getXMLDOC(actionName); + Map viewMap = new HashMap(); + View view = new View(); + view.setParameters(viewMap); + try { + Class classz = Class.forName(xmlDoc.get(actionName)); + LoginAction la = (LoginAction) classz.newInstance(); + la.setName(parameters.get("name")); + la.setPassword(parameters.get("password")); + Method exectue = classz.getMethod("execute", null); + Object result = exectue.invoke(la, null); + Field[] fields = classz.getDeclaredFields(); + for (Field field : fields) { + PropertyDescriptor pd = new PropertyDescriptor(field.getName(), classz); + Method readMethod = pd.getReadMethod(); + viewMap.put(field.getName(), (String) readMethod.invoke(la, null)); + } + view.setJsp(xmlDoc.get(result)); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IntrospectionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /* + * 0. 读取配置文件struts.xml 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象), + * 据parameters中的数据,调用对象的setter方法 例如parameters中的数据是 ("name"="test" , "password"="1234") , + * 那就应该调用 setName和setPassword方法 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" 3. + * 通过反射找到对象的所有getter方法(例如 getMessage), 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + * 放到View对象的parameters 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + * 放到View对象的jsp字段中。 + */ + return view; + } + /** + * @MethodName: getXMLDOC + * @Description: 解析xml文件 + * @param actionName + * @return + * @return: Map + */ + private static Map getXMLDOC(String actionName) { + Map xmldoc = new HashMap(); + // 解析struts.xml文件 + // 创建SAXReader的对象reader + SAXReader reader = new SAXReader(); + try { + // 通过reader对象的read方法读取struts.xml,得到document对象 + Document document = reader.read(new File("src/com/coderising/litestruts/struts.xml")); + // 获取根节点 + Element struts = document.getRootElement(); + // 迭代节点 + Iterator actions = struts.elementIterator(); + while (actions.hasNext()) { + Element action = (Element) actions.next(); + if (actionName.equals(action.attributeValue("name"))) { + xmldoc.put(action.attributeValue("name"), action.attributeValue("class")); + Iterator results = action.elementIterator(); + while (results.hasNext()) { + Element result = (Element) results.next(); + xmldoc.put(result.attributeValue("name"), result.getStringValue()); + } + break; + } + } + } catch (DocumentException e) { + e.printStackTrace(); + } + return xmldoc; + } + +} diff --git a/group12/446031103/src/com/coderising/litestruts/StrutsTest.java b/group12/446031103/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/group12/446031103/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group12/446031103/src/com/coderising/litestruts/View.java b/group12/446031103/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group12/446031103/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group12/446031103/src/com/coderising/litestruts/struts.xml b/group12/446031103/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..07f80b6476 --- /dev/null +++ b/group12/446031103/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/446031103/src/com/coding/basic/ArrayList.java b/group12/446031103/src/com/coding/basic/ArrayList.java index c627a7d2fa..bc3d75c3f6 100644 --- a/group12/446031103/src/com/coding/basic/ArrayList.java +++ b/group12/446031103/src/com/coding/basic/ArrayList.java @@ -2,6 +2,8 @@ import java.util.Arrays; + + /** * * arrayList集合-数组 @@ -11,10 +13,8 @@ * @date 2017年2月21日 下午3:49:24 */ public class ArrayList implements List { - // 记录ArrayList集合大小 private int size = 0; - // 初始化存储数组 - private Object[] elementData = new Object[100]; + private Object[] elementData = new Object[0]; /** * * 向最后插入元素 @@ -24,10 +24,9 @@ public class ArrayList implements List { * @see com.coding.basic.List#add(java.lang.Object) */ public void add(Object o){ - // 数组不够时增长 - growOrNot(size + 1); + ensureCapacity(size + 1); elementData[size] = o; - ++size; + size++; } /** * @@ -40,10 +39,10 @@ public void add(Object o){ */ public void add(int index, Object o){ validate(index); - growOrNot(size + 1); + ensureCapacity(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = o; - ++size; + size++; } /** * @@ -67,12 +66,12 @@ public Object get(int index){ * @return 删除的元素 * @see com.coding.basic.List#remove(int) */ - public Object remove(int index){ - Object oldValue = elementData[index]; + public Object remove(int index){ validate(index); + Object oldValue = elementData[index]; System.arraycopy(elementData, index + 1, elementData, index, size - index - 1); elementData[size] = null; - --size; + size--; return oldValue; } /** @@ -84,25 +83,24 @@ public Object remove(int index){ * @see com.coding.basic.List#size() */ public int size(){ - return size; + return this.size; } - + /** + * 迭代 + * @return + */ public Iterator iterator(){ - return null; + return new ArrayListIterator(); } /** - * - * 判断是否需要增长数组 - * - * @MethodName growOrNot - * @author msh - * @date 2017年2月21日 下午3:53:29 + * 判断是否需要数组增长 * @param minCapacity */ - private void growOrNot(int minCapacity) { - // 当增加长度大于数组长度时,增长 - if (minCapacity > elementData.length) { - elementData = Arrays.copyOf(elementData, elementData.length * 2); + private void ensureCapacity(int minCapacity) { + if(minCapacity>elementData.length){ + int newCapacity = Math.max(minCapacity, elementData.length*2); + Object[] newElementData = new Object[newCapacity]; + System.arraycopy(elementData, 0, newElementData, 0, elementData.length); } } /** @@ -118,4 +116,26 @@ private void validate(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } + /** + * + * @author Administrator + * + */ + private class ArrayListIterator implements Iterator{ + private int position; + private ArrayList list; + @Override + public boolean hasNext() { + return position < list.size(); + } + + @Override + public Object next() { + if (hasNext()) { + return list.get(position++); + } + return null; + } + + } } diff --git a/group12/446031103/src/com/coding/basic/LinkedList.java b/group12/446031103/src/com/coding/basic/LinkedList.java index de508694a0..33f6d79e65 100644 --- a/group12/446031103/src/com/coding/basic/LinkedList.java +++ b/group12/446031103/src/com/coding/basic/LinkedList.java @@ -1,5 +1,12 @@ package com.coding.basic; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.experimental.theories.Theories; + +import sun.reflect.Reflection; + /** * * LinkedList集合-链 @@ -222,4 +229,142 @@ public Node(Object data, Node next) { this.next = next; } } + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + for (int i = size; i <0; i--) { + Node last=(Node) get(i); + if(0==i) + last.next = null; + else + last.next = (Node) get(i-1); + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf(){ + + for (int i = 0; i < size%2; i++) { + remove(i); + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + for (int a = i; a < i+length; a++) { + remove(a); + } + + } + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public static int[] getElements(LinkedList list){ + int [] result =new int[list.size]; + Class callClass=Reflection.getCallerClass(); + for (int i = 0; i < list.size; i++) { + Node node=(Node) list.get(i); + try { + Method method=callClass.getDeclaredMethod("get", new Class[]{int.class}); + result[i]=(int) method.invoke(callClass, new Object[]{node.data}); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + for (int i = 0; i < list.size; i++) { + Node node=(Node) list.get(i); + for (int j = 0; j < size; j++) { + Node orgNode=(Node) get(i); + if (node.data.equals(orgNode.data)) { + remove(j); + } + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + for (int i = 0; i < size; i++) { + Node node=(Node) get(i); + for (int j = i+1; j < size; j++) { + Node newNode=(Node) get(j); + if(newNode.data.equals(node.data)) + remove(j); + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + for (int i = 0; i < size; i++) { + Node node=(Node) get(i); + if((int)node.data>min && (int)node.data fiboArray.length) { + fiboArray = Arrays.copyOf(fiboArray, fiboArray.length * 2); + } + fiboArray[++index] = now; + } + return Arrays.copyOf(fiboArray, index); + } + + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + * @throws Exception + */ + public int[] getPrimes(int max) throws Exception { + if (max < 2) { + return null; + } + int[] primes = new int[] { 2 }; + int index = 0; + int newPrimes = 3; + while (newPrimes < max) { + if (index + 2 > primes.length) { + primes = Arrays.copyOf(primes, primes.length * 2); + } + primes[++index] = newPrimes; + + boolean foundPrime = false; + while (!foundPrime) { + newPrimes += 2; + foundPrime = true; + int mid = newPrimes / 2 + 1; + for (int i = 3; i <= mid; i++) { + if (newPrimes % i == 0) { + foundPrime = false; + break; + } + } + } + } + + return Arrays.copyOf(primes, ++index); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int perfectNumber = 6; + if (max < perfectNumber) { + return null; + } + int[] perfectNumbers = new int[] { perfectNumber }; + + while (perfectNumber < max) { + perfectNumber++; + int sum = 0; + for (int i = 1; i < perfectNumber; i++) { + if (perfectNumber % i == 0) { + sum += i; + } + } + if (sum == perfectNumber) { + int[] newArr = new int[perfectNumbers.length + 1]; + System.arraycopy(perfectNumbers, 0, newArr, 0, perfectNumbers.length); + perfectNumbers = newArr; + perfectNumbers[perfectNumbers.length - 1] = perfectNumber; + } + } + return perfectNumbers; + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) { + if (array == null || array.length == 0) { + return null; + } + StringBuilder sb = new StringBuilder(); + sb.append(array[0]); + for (int i = 1; i < array.length; i++) { + sb.append(seperator + array[i]); + } + return sb.toString(); + } + +} diff --git a/group12/495473393/Code/src/week2/array/ArrayUtilTest.java b/group12/495473393/Code/src/week2/array/ArrayUtilTest.java new file mode 100644 index 0000000000..7f5cf05025 --- /dev/null +++ b/group12/495473393/Code/src/week2/array/ArrayUtilTest.java @@ -0,0 +1,150 @@ +/** + * + */ +package week2.array; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author TangHaoJie + * + */ +public class ArrayUtilTest { + + private ArrayUtil au; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + au = new ArrayUtil(); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + /** + * {@link week2.array.ArrayUtil#reverseArray(int[])} 的测试方法。 + */ + @Test + public void testReverseArray() { + int[] a1 = null; + au.reverseArray(a1); + assertArrayEquals(null, a1); + + int[] a2 = new int[0]; + au.reverseArray(a2); + assertArrayEquals(new int[0], a2); + + int[] a3 = new int[] { 1, 2, 3, 4, 5, 6 }; + au.reverseArray(a3); + assertArrayEquals(new int[] { 6, 5, 4, 3, 2, 1 }, a3); + } + + /** + * {@link week2.array.ArrayUtil#removeZero(int[])} 的测试方法。 + */ + @Test + public void testRemoveZero() { + int[] a1 = null; + int[] b1 = au.removeZero(a1); + assertArrayEquals(b1, a1); + + int[] a2 = new int[0]; + int[] b2 = au.removeZero(a2); + assertArrayEquals(b2, a2); + + int[] a3 = new int[] { 1, 2, 3, 4, 5, 6 }; + int[] b3 = au.removeZero(a3); + assertArrayEquals(b3, a3); + + int[] a4 = new int[] { 0, 0, 1, 2, 0, 3, 4, 0, 5, 6 }; + int[] b4 = au.removeZero(a4); + assertArrayEquals(b4, new int[] { 1, 2, 3, 4, 5, 6 }); + + int[] a5 = new int[] { 1, 2, 0, 3, 4, 0, 5, 6, 0, 0, 0 }; + int[] b5 = au.removeZero(a5); + assertArrayEquals(b5, new int[] { 1, 2, 3, 4, 5, 6 }); + } + + /** + * {@link week2.array.ArrayUtil#merge(int[], int[])} 的测试方法。 + */ + @Test + public void testMerge() { + int[] a1 = null; + int[] b1 = null; + int[] c1 = au.merge(a1, b1); + assertArrayEquals(c1, null); + + int[] a2 = new int[0]; + int[] b2 = new int[0]; + int[] c2 = au.merge(a2, b2); + assertArrayEquals(c2, new int[0]); + + int[] a3 = new int[] { 1, 3, 5, 7, 9 }; + int[] b3 = new int[] { 2, 4, 6, 8, 10 }; + int[] c3 = au.merge(a3, b3); + assertArrayEquals(c3, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + } + + /** + * {@link week2.array.ArrayUtil#grow(int[], int)} 的测试方法。 + */ + @Test + public void testGrow() { + int[] a1 = null; + int[] b1 = au.grow(a1, 0); + assertArrayEquals(b1, a1); + + int[] a2 = new int[0]; + int[] b2 = au.grow(a2, 0); + assertArrayEquals(b2, a2); + + int[] a3 = new int[] { 1, 2 }; + int[] b3 = au.grow(a3, -10); + assertArrayEquals(b3, a3); + + int[] a4 = new int[] { 1, 2 }; + int[] b4 = au.grow(a4, 5); + assertArrayEquals(b4, new int[] { 1, 2, 0, 0, 0, 0, 0 }); + } + + /** + * {@link week2.array.ArrayUtil#fibonacci(int)} 的测试方法。 + */ + @Test + public void testFibonacci() { + } + + /** + * {@link week2.array.ArrayUtil#getPrimes(int)} 的测试方法。 + */ + @Test + public void testGetPrimes() { + } + + /** + * {@link week2.array.ArrayUtil#getPerfectNumbers(int)} 的测试方法。 + */ + @Test + public void testGetPerfectNumbers() { + } + + /** + * {@link week2.array.ArrayUtil#join(int[], java.lang.String)} 的测试方法。 + */ + @Test + public void testJoin() { + } + +} diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/LoginAction.java b/group12/495473393/Code/src/week2/litestruts/LoginAction.java similarity index 96% rename from group20/592146505/coderising/src/org/wsc/litestruts/LoginAction.java rename to group12/495473393/Code/src/week2/litestruts/LoginAction.java index bb23f5eebb..d8daf1c835 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/LoginAction.java +++ b/group12/495473393/Code/src/week2/litestruts/LoginAction.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts; +package week2.litestruts; /** * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 diff --git a/group12/495473393/Code/src/week2/litestruts/Struts.java b/group12/495473393/Code/src/week2/litestruts/Struts.java new file mode 100644 index 0000000000..bafaaafd8c --- /dev/null +++ b/group12/495473393/Code/src/week2/litestruts/Struts.java @@ -0,0 +1,34 @@ +package week2.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/StrutsTest.java b/group12/495473393/Code/src/week2/litestruts/StrutsTest.java similarity index 97% rename from group20/592146505/coderising/src/org/wsc/litestruts/StrutsTest.java rename to group12/495473393/Code/src/week2/litestruts/StrutsTest.java index 8101e95fe3..9187ef02f2 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/StrutsTest.java +++ b/group12/495473393/Code/src/week2/litestruts/StrutsTest.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts; +package week2.litestruts; import java.util.HashMap; import java.util.Map; diff --git a/group12/495473393/Code/src/week2/litestruts/View.java b/group12/495473393/Code/src/week2/litestruts/View.java new file mode 100644 index 0000000000..01a422a808 --- /dev/null +++ b/group12/495473393/Code/src/week2/litestruts/View.java @@ -0,0 +1,23 @@ +package week2.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group12/495473393/Code/src/week2/litestruts/struts.xml b/group12/495473393/Code/src/week2/litestruts/struts.xml new file mode 100644 index 0000000000..a6cfe43e6c --- /dev/null +++ b/group12/495473393/Code/src/week2/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/495473393/Coding/src/Base/LinkedList.java b/group12/495473393/Coding/src/Base/LinkedList.java deleted file mode 100644 index 0d4ce20167..0000000000 --- a/group12/495473393/Coding/src/Base/LinkedList.java +++ /dev/null @@ -1,46 +0,0 @@ -package Base; - -public class LinkedList implements List { - - private Node head; - - public void add(Object o){ - - } - public void add(int index , Object o){ - - } - public Object get(int index){ - return null; - } - public Object remove(int index){ - return null; - } - - public int size(){ - return -1; - } - - public void addFirst(Object o){ - - } - public void addLast(Object o){ - - } - public Object removeFirst(){ - return null; - } - public Object removeLast(){ - return null; - } - public Iterator iterator(){ - return null; - } - - - private static class Node{ - Object data; - Node next; - - } -} diff --git a/group12/563253496/week2/out/production/week2/litestruts/struts.xml b/group12/563253496/week2/out/production/week2/litestruts/struts.xml new file mode 100644 index 0000000000..bfc639857c --- /dev/null +++ b/group12/563253496/week2/out/production/week2/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/563253496/week2/src/array/ArrayUtil.java b/group12/563253496/week2/src/array/ArrayUtil.java new file mode 100644 index 0000000000..d9236e72d4 --- /dev/null +++ b/group12/563253496/week2/src/array/ArrayUtil.java @@ -0,0 +1,329 @@ +package array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + * 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + * 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + int temp; + for (int i = 0; i < origin.length / 2; i++) { + temp = origin[i]; + origin[i] = origin[origin.length - i - 1]; + origin[origin.length - i - 1] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + int count = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] == 0) { + count++; + } + } + int[] newArray = new int[oldArray.length - count]; + int flag = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + newArray[flag] = oldArray[i]; + flag++; + } else { + continue; + } + } + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) { + + /* + int[] temp = new int[array1.length + array2.length]; + int count = array1.length; + int point = array1.length; + for (int i = 0; i < array1.length; i++) { + temp[i] = array1[i]; + } + boolean flag = true; + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array1.length; j++) { + if (array1[j] == array2[i]) { + flag = false; + } + } + if (flag) { + temp[count]=array2[i]; + count++; + } + flag = true; + } + */ + if (array1.length == 0) { + return array2; + } + if (array2.length == 0) { + return array1; + } + + int[] temp = new int[array1.length + array2.length]; + int ap = 0; + int bp = 0; + int count = 0; + while (ap < array1.length && bp < array2.length) { + if (array1[ap] == array2[bp]) { + temp[count] = array1[ap]; + ap++; + bp++; + count++; + } else if (array1[ap] > array2[bp]) { + temp[count] = array2[bp]; + bp++; + count++; + } else { + temp[count] = array1[ap]; + ap++; + count++; + } + } + if (ap == array1.length) { + for (int i = bp; i < array2.length; i++) { + temp[count] = array2[i]; + count++; + } + } else if (bp == array2.length) { + for (int i = ap; i < array1.length; i++) { + temp[count] = array1[i]; + count++; + } + + + } + int array3[] = new int[count]; + System.arraycopy(temp, 0, array3, 0, count); + + return array3; + /*int[] temp = new int[array2.length]; + boolean flag = true; + int count = 0; + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array1.length; j++) { + if (array2[j] == array1[i]) { + flag = false; + } + } + if (flag) { + temp[count] = array2[i]; + count++; + } + } + if (count == 0) { + return array1; + } + + int ap = 0; //数组1的指针 + int bp = 0; //数组2的指针 + int[] array3 = new int[count + array1.length]; + for (int i = 0; i < array3.length; i++) { + if (array1[ap] > array2[bp]) { + array3[i] = array2[bp]; + bp++; + }else { + array3[i] = array1[ap]; + ap++; + } + + } +*/ + + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + int[] newArray = new int[oldArray.length + size]; + for (int i = 0; i < oldArray.length; i++) { + newArray[i] = oldArray[i]; + } + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + + if (max == 1) { + return null; + } + int a = 1; + int b = 1; + int[] result = {1, 1}; + int[] temp; + while (b < max) { + + b = a + b; + a = b - a; + temp = result; + result = new int[result.length + 1]; + + for (int i = 0; i < temp.length; i++) { + result[i] = temp[i]; + } + result[result.length - 1] = b; + } + temp = result; + result = new int[result.length - 1]; + for (int i = 0; i < result.length; i++) { + result[i] = temp[i]; + } + return result; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + /* int[] result = null; + int[] temp = null; + if (max < 2) { + return null; + } + boolean flag = true; + for (int i = 2; i < max; i++) { + for (int j = 2; j * j < i; j++) { + if (i % j == 0) { + flag = false; + } + } + if (flag) { + if (result == null) { + result = new int[1]; + result[0] = i; + } else { + temp = result; + result = new int[result.length + 1]; + for (int j = 0; j < temp.length; j++) { + result[j] = temp[j]; + } + result[result.length - 1] = i; + } + } + flag = true; + } + + return result;*/ + if (max < 2) { + return null; + } + int[] result = {2}; + int[] temp ; + boolean flag = true; + for (int i = 3; i < max; i++) { + for (int j = 2; j * j <= i; j++) { + if (i % j == 0){ + flag = false; + } + } + if (flag) { + temp=result; + result=new int[temp.length+1]; + System.arraycopy(temp,0,result,0,temp.length); + result[result.length-1]=i; + } + flag=true; + + } + return result; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int[] result = {}; + int[] temp = null; + int count = 0; + for (int i = 1; i < max; i++) { + for (int j = 1; j < i; j++) { + if (i % j == 0) { + count += j; + } + } + if (count == i) { + temp = result; + result = new int[temp.length + 1]; + for (int j = 0; j < temp.length; j++) { + result[j] = temp[j]; + } + result[result.length - 1] = i; + } + + } + return result; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @param seperator + * @return + */ + public String join(int[] array, String seperator) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < array.length - 1; i++) { + sb.append(array[i]); + sb.append(seperator); + } + sb.append(array[array.length - 1]); + return sb.toString(); + + } + + +} diff --git a/group12/563253496/week2/src/litestruts/LoginAction.java b/group12/563253496/week2/src/litestruts/LoginAction.java new file mode 100644 index 0000000000..bba4c11c9f --- /dev/null +++ b/group12/563253496/week2/src/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group12/563253496/week2/src/litestruts/Struts.java b/group12/563253496/week2/src/litestruts/Struts.java new file mode 100644 index 0000000000..4c478cae5e --- /dev/null +++ b/group12/563253496/week2/src/litestruts/Struts.java @@ -0,0 +1,128 @@ +package litestruts; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法,例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + //读取配置文件 + + SAXReader reader = new SAXReader(); + try { + Document document = reader.read("src/litestruts/struts.xml"); + Element root = document.getRootElement(); + Element temp = null; + + /* + *保存root的子节点 + Map lables = new HashMap(); + + for (int i = 0; i < root.elements().size(); i++) { + temp = (Element) root.elements().get(i); + lables.put(temp.attribute(0).getText(), i); + } + */ + + Map viewResult = new HashMap<>(); + Map resultLable = new HashMap<>(); + Map firstLayorNode = new HashMap<>(); + + //保存根节点的子节点 + for (int i = 0; i < root.elements().size(); i++) { + temp = (Element)root.elements().get(i); + firstLayorNode.put(temp.attribute("name").getText(),i); + } + + View view = new View(); + + Element actionLable = (Element)root.elements().get(firstLayorNode.get(actionName)); + + if (actionName.equals("login")) { + + + for (int i = 0; i < actionLable.elements().size(); i++) { + temp = (Element) actionLable.elements().get(i); + resultLable.put(temp.attribute("name").getText(), temp.getText()); + } + + + Class clazz = Class.forName(actionLable.attribute("class").getText()); + + LoginAction la = (LoginAction) clazz.newInstance(); + la.setName(parameters.get("name")); + la.setPassword(parameters.get("password")); + + Method m = clazz.getMethod("execute"); + String result = (String) m.invoke(la); + + + view.setJsp(resultLable.get(result)); + + + m = clazz.getMethod("getMessage"); + result = (String) m.invoke(la); + viewResult.put("message", result); + + m = clazz.getMethod("getName"); + result = (String) m.invoke(la); + viewResult.put("name", result); + + m = clazz.getMethod("getPassword"); + result = (String)m.invoke(la); + viewResult.put("password", result); + + view.setParameters(viewResult); + return view; + } + + + } catch (DocumentException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + + return null; + } + +} diff --git a/group12/563253496/week2/src/litestruts/StrutsTest.java b/group12/563253496/week2/src/litestruts/StrutsTest.java new file mode 100644 index 0000000000..d6be3a2d14 --- /dev/null +++ b/group12/563253496/week2/src/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group12/563253496/week2/src/litestruts/View.java b/group12/563253496/week2/src/litestruts/View.java new file mode 100644 index 0000000000..1eed614744 --- /dev/null +++ b/group12/563253496/week2/src/litestruts/View.java @@ -0,0 +1,23 @@ +package litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group12/563253496/week2/src/litestruts/struts.xml b/group12/563253496/week2/src/litestruts/struts.xml new file mode 100644 index 0000000000..bfc639857c --- /dev/null +++ b/group12/563253496/week2/src/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group12/563253496/week2/src/litestruts/test.java b/group12/563253496/week2/src/litestruts/test.java new file mode 100644 index 0000000000..f29f7ee366 --- /dev/null +++ b/group12/563253496/week2/src/litestruts/test.java @@ -0,0 +1,44 @@ +package litestruts; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +/** + * Created by bdl19 on 2017/3/2. + */ +public class test { + public static void main(String[] args) { + SAXReader reader = new SAXReader(); + try { + Document document = reader.read("src/litestruts/struts.xml"); + Element root = document.getRootElement(); + System.out.println(root.elements().size()); + + +/* + + String s = "login"; + String string = "login"; + System.out.println(root.getName()); + Element action = root.element("action"); + System.out.print(action.getName()); + System.out.print(action.attribute("name").getText()); + System.out.print(action.attribute("name").getText()); + String str = action.attribute("name").getText(); + if (str.equals(s)) { + System.out.println(123123); + System.out.println("123"); + // Class clazz = Class.forName(action.attribute("class")); + } + System.out.println(s); + System.out.println(str); + +*/ + + } catch (DocumentException e) { + e.printStackTrace(); + } + } +} diff --git a/group12/563253496/week2/src/test/array/ArrayUtilTest.java b/group12/563253496/week2/src/test/array/ArrayUtilTest.java new file mode 100644 index 0000000000..57a0c6d648 --- /dev/null +++ b/group12/563253496/week2/src/test/array/ArrayUtilTest.java @@ -0,0 +1,166 @@ +package test.array; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.Before; +import org.junit.After; + +import array.ArrayUtil; + +import java.lang.reflect.Array; + +/** + * ArrayUtil Tester. + * + * @author + * @version 1.0 + * @since
 2, 2017
+ */ +public class ArrayUtilTest { + + @Before + public void before() throws Exception { + + } + + @After + public void after() throws Exception { + + } + + /** + * Method: reverseArray(int[] origin) + */ + @Test + public void testReverseArray() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + int[] a = {7, 9, 30, 3}; + int[] b = {3, 30, 9, 7}; + au.reverseArray(a); + for (int i = 0; i < a.length; i++) { + Assert.assertEquals(b[i], a[i]); + } + + a = new int[]{7, 9, 30, 3, 4}; + b = new int[]{4, 3, 30, 9, 7}; + au.reverseArray(a); + for (int i = 0; i < a.length; i++) { + Assert.assertEquals(b[i], a[i]); + } + + } + + /** + * Method: removeZero(int[] oldArray) + */ + @Test + public void testRemoveZero() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + + int oldArr[] = {1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5}; + int result[] = au.removeZero(oldArr); + int exResult[] = {1, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5}; + Assert.assertEquals(result.length,exResult.length); + for (int i = 0; i < result.length; i++) { + Assert.assertEquals(result[i], exResult[i]); + + } + } + + /** + * Method: merge(int[] array1, int[] array2) + */ + @Test + public void testMerge() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + int[] a1 = {3, 5, 7, 8}; + int[] a2 = {4, 5, 6, 7}; + int[] a3 = {3, 4, 5, 6, 7, 8}; + int[] result = au.merge(a1,a2); + Assert.assertEquals(a3.length, result.length); + for (int i = 0; i < result.length; i++) { + Assert.assertEquals(a3[i],result[i]); + } + } + + /** + * Method: grow(int[] oldArray, int size) + */ + @Test + public void testGrow() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + + int[] oldArray = {2,3,6}; + int size = 3; + + int[] newArray = au.grow(oldArray,size); + int[] exArray = {2,3,6,0,0,0}; + for (int i = 0; i < newArray.length; i++) { + Assert.assertEquals(exArray[i],newArray[i]); + } + + } + + /** + * Method: fibonacci(int max) + */ + @Test + public void testFibonacci() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + int[] exArray = {1,1,2,3,5,8,13}; + int[] newArray = au.fibonacci(14); + for (int i = 0; i < newArray.length; i++) { + Assert.assertEquals(exArray[i],newArray[i]); + } + } + + /** + * Method: getPrimes(int max) + */ + @Test + public void testGetPrimes() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + int[] exArray = {2,3,5,7,11,13,17,19}; + int[] newArray = au.getPrimes(23); + for (int i = 0; i < newArray.length; i++) { + Assert.assertEquals(exArray[i],newArray[i]); + } + } + + /** + * Method: getPerfectNumbers(int max) + */ + @Test + public void testGetPerfectNumbers() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + int exArray[] = {6,28,496}; + int[] newArray = au.getPerfectNumbers(1000); + for (int i = 0; i < newArray.length; i++) { + Assert.assertEquals(exArray[i],newArray[i]); + } + + + } + + /** + * Method: join(int[] array, String seperator) + */ + @Test + public void testJoin() throws Exception { +//TODO: Test goes here... + ArrayUtil au = new ArrayUtil(); + String exS = "3-8-9"; + int[] array= {3,8,9}; + String result = au.join(array,"-"); + Assert.assertEquals(exS,result); + } + + +} diff --git a/group12/563253496/week3/src/com/coderising/array/ArrayUtil.java b/group12/563253496/week3/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..e5ddb476a6 --- /dev/null +++ b/group12/563253496/week3/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coderising.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/group12/563253496/week3/src/com/coderising/litestruts/LoginAction.java b/group12/563253496/week3/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/group12/563253496/week3/src/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group12/563253496/week3/src/com/coderising/litestruts/Struts.java b/group12/563253496/week3/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/group12/563253496/week3/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/group12/563253496/week3/src/com/coderising/litestruts/StrutsTest.java b/group12/563253496/week3/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/group12/563253496/week3/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group12/563253496/week3/src/com/coderising/litestruts/View.java b/group12/563253496/week3/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group12/563253496/week3/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group12/495473393/Coding/src/Base/ArrayList.java b/group12/563253496/week3/src/com/coding/basic/ArrayList.java similarity index 93% rename from group12/495473393/Coding/src/Base/ArrayList.java rename to group12/563253496/week3/src/com/coding/basic/ArrayList.java index 0b99f87873..1f185736f9 100644 --- a/group12/495473393/Coding/src/Base/ArrayList.java +++ b/group12/563253496/week3/src/com/coding/basic/ArrayList.java @@ -1,4 +1,4 @@ -package Base; +package com.coding.basic; public class ArrayList implements List { diff --git a/group10/904627477/src/com/coding/BinaryTreeNode.java b/group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java similarity index 91% rename from group10/904627477/src/com/coding/BinaryTreeNode.java rename to group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java index fe50e3d1ae..d7ac820192 100644 --- a/group10/904627477/src/com/coding/BinaryTreeNode.java +++ b/group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java @@ -1,32 +1,32 @@ -package com.coding; - -public class BinaryTreeNode { - - private Object data; - private BinaryTreeNode left; - private BinaryTreeNode right; - - public Object getData() { - return data; - } - public void setData(Object data) { - this.data = data; - } - public BinaryTreeNode getLeft() { - return left; - } - public void setLeft(BinaryTreeNode left) { - this.left = left; - } - public BinaryTreeNode getRight() { - return right; - } - public void setRight(BinaryTreeNode right) { - this.right = right; - } - - public BinaryTreeNode insert(Object o){ - return null; - } - -} +package com.coding.basic; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} diff --git a/group12/563253496/week3/src/com/coding/basic/Iterator.java b/group12/563253496/week3/src/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/group12/563253496/week3/src/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group12/563253496/week3/src/com/coding/basic/LinkedList.java b/group12/563253496/week3/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..f50db4c7a1 --- /dev/null +++ b/group12/563253496/week3/src/com/coding/basic/LinkedList.java @@ -0,0 +1,345 @@ +package com.coding.basic; + + +import javax.management.ListenerNotFoundException; + +public class LinkedList implements List { + + private Node head = new Node(-1); + + private int size = 0; + + public void add(Object o) { + Node addNode = new Node(o); + if (size == 0) { + head.next = addNode; + size++; + } else { + /*Node n = getNode(size); + n.next = temp; + size++;*/ + Node temp = head; + for (int i = 0; i < size; i++) { + temp = temp.next; + } + temp.next = addNode; + size++; + } + + } + + + public String toString() { + Node temp = head; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < size; i++) { + + temp = temp.next; + sb.append(temp.data); + sb.append("->"); + + } + sb.deleteCharAt((sb.length() - 1)); + sb.deleteCharAt((sb.length() - 1)); + String result = sb.toString(); + return result; + } + + public void add(int index, Object o) { + /*if (index <= 0 || index > size) { + throw new IndexOutOfBoundsException(); + } + Node addNode = new Node(o); + Node temp = head; + for (int i = 1; i <= index; i++) { + temp = temp.next; + }*/ + } + + public Object get(int index) { + if (index <= 0 || index > size) { + throw new IndexOutOfBoundsException(); + } + Node temp = head; + for (int i = 1; i <= index; i++) { + temp = temp.next; + + } + return temp.data; + } + + public Object remove(int index) { + return null; + } + +/* public Node getNode(int index) { + Node temp = head; + for (int i = 1; i <= index; i++) { + temp = head.next; + } + return temp; + }*/ + + public int size() { + return this.size; + } + + public void addFirst(Object o) { + Node addNode = new Node(o); + addNode.next = head.next; + head.next = addNode; + size++; + + } + + public void addLast(Object o) { + + } + + public Object removeFirst() { + return null; + } + + public Object removeLast() { + return null; + } + + public Iterator iterator() { + return null; + } + + + private static class Node { + Object data; + Node next; + + Node() { + this.data = null; + this.next = null; + } + + Node(Object o) { + this.data = o; + this.next = null; + } + + Node(Node n) { + this.data = n.data; + this.next = n.next; + } + + public boolean hasNext() { + if (this.next == null) { + return false; + } else { + return true; + } + } + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + /*LinkedList ll = new LinkedList(); + ll.add(3); + ll.add(7); + ll.add(8); + ll.add(9); + ll.add(10); + System.out.println(ll);*/ + //System.out.println(this); + LinkedList result = new LinkedList(); + Node temp = this.head; + for (int i = 0; i < this.size(); i++) { + temp = temp.next; + result.addFirst(temp.data); + } + this.head = result.head; + //System.out.println(this); + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf() { + Node temp = this.head; + for (int i = 0; i < (int) (this.size / 2); i++) { + temp = temp.next; + + } + this.size = this.size - this.size / 2; + this.head.next = temp.next; + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + Node startNode = this.head; + + for (int j = 0; j < i; j++) { + startNode = startNode.next; + + } + Node endNode = startNode; + for (int j = 0; j < length; j++) { + endNode = endNode.next; + } + startNode.next = endNode.next; + size = size - length; + + } + + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * + * @param list + */ + public int[] getElements(LinkedList list) { + int[] result = new int[list.size()]; + Node node = list.head; + + for (int i = 0; i < result.length; i++) { + node = node.next; + result[i] = (int) (this.get(((int) (node.data)) + 1)); + } + return result; + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * + * @param list + */ + + public void subtract(LinkedList list) { + Node posNode = this.head; + Node listNode = list.head.next; + + for (int i = 0; i < list.size(); i++) { + while (posNode.next.data != listNode.data) { + posNode = posNode.next; + } + posNode.next = posNode.next.next; + listNode = listNode.next; + } + this.size = size - list.size(); + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + Node posnode = this.head; + //Node temp; + while(posnode.hasNext()){ + if(posnode.data==posnode.next.data){ + posnode.next=posnode.next.next; + this.size--; + continue; + } + posnode=posnode.next; + } + + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + Node startPos = this.head; + Node endPos; + int count1 = 0; + int count2 = 1; + for (int i = 0; i < this.size(); i++) { + if ((int) startPos.next.data > min) { + break; + } + startPos = startPos.next; + count1++; + } + endPos = startPos.next; + for (int i = count1; i < this.size(); i++) { + if ((int) endPos.data > max) { + break; + } + endPos = endPos.next; + count2++; + } + size = size - count2; + startPos.next = endPos; + } + + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) { + LinkedList result = new LinkedList(); + Node a = this.head.next; + Node b = list.head.next; + + while (a.hasNext() && b.hasNext()) { + if ((int) a.data == (int) b.data) { + result.add(a.data); + a = a.next; + b = b.next; + } else if ((int) a.data > (int) b.data) { + b = b.next; + } else if ((int) a.data < (int) b.data) { + a = a.next; + } + + + } + if (a.hasNext() == false) { + while (b.hasNext() == true) { + if ((int) a.data == (int) b.data) { + result.add(a.data); + break; + } else { + b = b.next; + } + } + } else if (b.hasNext() == false) { + while (a.hasNext() == true) { + if ((int) a.data == (int) b.data) { + result.add(a.data); + break; + } else { + a = a.next; + } + } + } + return result; + + + } + + +} diff --git a/group12/563253496/week3/src/com/coding/basic/List.java b/group12/563253496/week3/src/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/group12/563253496/week3/src/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group12/495473393/Coding/src/Base/Queue.java b/group12/563253496/week3/src/com/coding/basic/Queue.java similarity index 88% rename from group12/495473393/Coding/src/Base/Queue.java rename to group12/563253496/week3/src/com/coding/basic/Queue.java index 9c2948d7e3..36e516e266 100644 --- a/group12/495473393/Coding/src/Base/Queue.java +++ b/group12/563253496/week3/src/com/coding/basic/Queue.java @@ -1,4 +1,4 @@ -package Base; +package com.coding.basic; public class Queue { diff --git a/group12/495473393/Coding/src/Base/Stack.java b/group12/563253496/week3/src/com/coding/basic/Stack.java similarity index 91% rename from group12/495473393/Coding/src/Base/Stack.java rename to group12/563253496/week3/src/com/coding/basic/Stack.java index 8f59343d4b..a5a04de76d 100644 --- a/group12/495473393/Coding/src/Base/Stack.java +++ b/group12/563253496/week3/src/com/coding/basic/Stack.java @@ -1,4 +1,4 @@ -package Base; +package com.coding.basic; public class Stack { private ArrayList elementData = new ArrayList(); diff --git a/group12/563253496/week3/src/test/com/coding/basic/LinkedListTest.java b/group12/563253496/week3/src/test/com/coding/basic/LinkedListTest.java new file mode 100644 index 0000000000..d00b12ea3e --- /dev/null +++ b/group12/563253496/week3/src/test/com/coding/basic/LinkedListTest.java @@ -0,0 +1,297 @@ +package test.com.coding.basic; + +import com.coding.basic.LinkedList; +import org.junit.Assert; +import org.junit.Test; +import org.junit.Before; +import org.junit.After; +import sun.awt.image.ImageWatched; + +/** + * LinkedList Tester. + * + * @author + * @version 1.0 + * @since
 9, 2017
+ */ +public class LinkedListTest { + + @Before + public void before() throws Exception { + } + + @After + public void after() throws Exception { + } + + /** + * Method: add(Object o) + */ + @Test + public void testAddO() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: toString() + */ + @Test + public void testToString() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: add(int index, Object o) + */ + @Test + public void testAddForIndexO() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: get(int index) + */ + @Test + public void testGet() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: remove(int index) + */ + @Test + public void testRemoveIndex() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: getNode(int index) + */ + @Test + public void testGetNode() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: size() + */ + @Test + public void testSize() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: addFirst(Object o) + */ + @Test + public void testAddFirst() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: addLast(Object o) + */ + @Test + public void testAddLast() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: removeFirst() + */ + @Test + public void testRemoveFirst() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: removeLast() + */ + @Test + public void testRemoveLast() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: iterator() + */ + @Test + public void testIterator() throws Exception { +//TODO: Test goes here... + } + + /** + * Method: reverse() + */ + @Test + public void testReverse() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(3); + ll.add(7); + ll.add(10); + ll.reverse(); + Assert.assertEquals("10->7->3", ll.toString()); + + } + + /** + * Method: removeFirstHalf() + */ + @Test + public void testRemoveFirstHalf() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(2); + ll.add(5); + ll.add(7); + ll.add(8); + ll.add(10); + ll.removeFirstHalf(); + Assert.assertEquals("7->8->10", ll.toString()); + } + + /** + * Method: remove(int i, int length) + */ + @Test + public void testRemoveForILength() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(1); + ll.add(2); + ll.add(3); + ll.add(4); + ll.add(5); + ll.add(6); + ll.add(7); + ll.remove(2, 2); + Assert.assertEquals("1->2->5->6->7", ll.toString()); + + } + + /** + * Method: getElements(LinkedList list) + */ + @Test + public void testGetElements() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(11); + ll.add(101); + ll.add(201); + ll.add(301); + ll.add(401); + ll.add(501); + ll.add(601); + ll.add(701); + LinkedList listB = new LinkedList(); + listB.add(1); + listB.add(3); + listB.add(4); + listB.add(6); + int[] result = ll.getElements(listB); + int[] exresult = {101, 301, 401, 601}; + for (int i = 0; i < result.length; i++) { + Assert.assertEquals(exresult[i], result[i]); + } + //Assert.assertEquals("[101,301,401,601]",result.toString()); + } + + /** + * Method: subtract(LinkedList list) + */ + @Test + public void testSubtract() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(1); + ll.add(2); + ll.add(3); + ll.add(4); + ll.add(5); + ll.add(6); + LinkedList listB = new LinkedList(); + listB.add(1); + listB.add(3); + listB.add(5); + ll.subtract(listB); + Assert.assertEquals("2->4->6", ll.toString()); + + } + + /** + * Method: removeDuplicateValues() + */ + @Test + public void testRemoveDuplicateValues() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(1); + ll.add(2); + ll.add(2); + ll.add(2); + ll.add(3); + ll.add(4); + ll.add(4); + ll.add(4); + ll.add(4); + ll.removeDuplicateValues(); + Assert.assertEquals("1->2->3->4",ll.toString()); + + } + + /** + * Method: removeRange(int min, int max) + */ + @Test + public void testRemoveRange() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + ll.add(1); + ll.add(2); + ll.add(3); + ll.add(4); + ll.add(5); + ll.add(6); + ll.add(7); + ll.add(8); + ll.removeRange(3,8); + Assert.assertEquals("1->2",ll.toString()); + + } + + /** + * Method: intersection(LinkedList list) + */ + @Test + public void testIntersection() throws Exception { +//TODO: Test goes here... + LinkedList ll = new LinkedList(); + LinkedList l = new LinkedList(); + ll.add(1); + ll.add(2); + ll.add(3); + ll.add(4); + ll.add(5); + ll.add(6); + l.add(2); + l.add(4); + l.add(6); + l.add(7); + l.add(8); + l.add(9); + LinkedList re = ll.intersection(l); + Assert.assertEquals("2->4->6",re.toString()); + } + + /** + * Method: main(String[] args) + */ + @Test + public void testMain() throws Exception { +//TODO: Test goes here... + } + + +} diff --git a/group13/1274639949/Exercise/src/lesson01/ArrayList.java b/group13/1274639949/Exercise/src/lesson01/ArrayList.java new file mode 100644 index 0000000000..45fbd42c1a --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/ArrayList.java @@ -0,0 +1,198 @@ +package lesson01; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +public class ArrayList implements List { + + private static final int DEFAULT_CAPACITY = 20; + private static final int DEFAULT_INCREMENT = 20; + + private int size; + + private Object[] elementData; + + public ArrayList() { + this(DEFAULT_CAPACITY); + } + + public ArrayList(int capacity) { + size = 0; + elementData = new Object[capacity]; + } + + + @Override + public boolean add(E e) { + ensureCapacity(); + elementData[size] = e; + size++; + return true; + } + + private void ensureCapacity() { + if(size == elementData.length){ + elementData = Arrays.copyOf(elementData, elementData.length + DEFAULT_INCREMENT); + } + } + + @Override + public void add(int index, E element) { + if(index < 0 || index > size){ + throw new IndexOutOfBoundsException("Error index :" + index); + } + ensureCapacity(); + System.arraycopy(element, index, element, index + 1, size - index); + elementData[index] = element; + size++; + } + + @Override + + public void clear() { + elementData = new Object[elementData.length]; + size = 0; + } + + @Override + public boolean contains(Object o) { + if(o == null){ + for(int i = 0; i < size; i++){ + if(elementData[i] == null){ + return true; + } + } + }else{ + for(int i = 0; i < size; i++){ + if(o.equals(elementData[i])){ + return true; + } + } + } + return false; + } + + @Override + public int indexOf(Object o) { + if(o == null){ + for(int i = 0; i < size; i++){ + if(elementData[i] == null){ + return i; + } + } + }else{ + for(int i = 0; i < size; i++){ + if(o.equals(elementData[i])){ + return i; + } + } + } + return -1; + } + + @SuppressWarnings("unchecked") + @Override + public E get(int index) { + checkIndex(index); + return (E) elementData[index]; + } + + private void checkIndex(int index) { + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("Illegal index:" + index); + } + } + + @SuppressWarnings("unchecked") + @Override + public E remove(int index) { + checkIndex(index); + + E e = (E) elementData[index]; + //此处应注意要判断index是否为elementData最后一个元素的下标,因为在下面的arrayCopy方法中要访问index+1的位置,此时有可能发生数组越界。 + if(index == size -1){ + size --; + }else{ + System.arraycopy(elementData, index + 1, elementData, index, size - index - 1); + } + return e; + } + + @Override + public boolean remove(Object o) { + int index = indexOf(o); + if(index >= 0){ + remove(index); + return true; + }else{ + return false; + } + } + + @SuppressWarnings("unchecked") + @Override + public E set(int index, E element) { + checkIndex(index); + E e = (E)elementData[index]; + elementData[index] = element; + return e; + } + + @Override + public int size() { + return size; + } + + @Override + public Object[] toArray() { + return Arrays.copyOf(elementData, size); + } + + /** + * 将ArrayList中全部元素存入一个运行时确定类型的数组中 + * @param t + * @return + */ + @SuppressWarnings("unchecked") + public T[] toArray(T[] t){ + if(t.length < size){ + t = (T[]) Arrays.copyOf(elementData, size, t.getClass()); + }else{ + System.arraycopy(elementData, 0, t, 0, size); + } + return t; + } + + @Override + public Iterator iterator() { + return new Iter(); + } + + private final class Iter implements Iterator{ + + int pos = 0; + int lastRet = -1; + + @Override + public boolean hasNext() { + return pos < size; + } + + @Override + public E next() { + if(!hasNext()){ + throw new NoSuchElementException(); + } + lastRet = pos++; + return get(lastRet); + } + + @Override + public void remove() { + if(lastRet < 0){ + throw new IllegalStateException(); + } + ArrayList.this.remove(lastRet); + } + } +} diff --git a/group13/1274639949/Exercise/src/lesson01/Iterator.java b/group13/1274639949/Exercise/src/lesson01/Iterator.java new file mode 100644 index 0000000000..58a50847ac --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/Iterator.java @@ -0,0 +1,11 @@ +package lesson01; + +public interface Iterator { + + public boolean hasNext(); + + public E next(); + + public void remove(); + +} diff --git a/group13/1274639949/Exercise/src/lesson01/LinkedList.java b/group13/1274639949/Exercise/src/lesson01/LinkedList.java new file mode 100644 index 0000000000..d4c0006c95 --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/LinkedList.java @@ -0,0 +1,294 @@ +package lesson01; + +import java.util.NoSuchElementException; + +public class LinkedList implements List { + + private int size; + private Node head; + private Node last; + private Node temp; + + public LinkedList() { + head = new Node(); + } + + + @Override + public boolean add(E e) { + add(size, e); + return true; + } + + @Override + public void add(int index, E element) { + if(index < 0 || index > size){ + throw new IndexOutOfBoundsException("Error index:" + index); + } + temp = new Node(); + temp.data = element; + if(last == null){ + //链表中还没有元素 + head.next = temp; + temp.pre = head; + last = temp; + }else if(index == size){ + //链表中已经有元素,在最后一个元素后面添加元素 + last.next = temp; + temp.pre = last; + last = temp; + }else{ + Node pos = head.next; + for(int i = 0; i < index; i++){ + pos = pos.next; + } + + temp.pre = pos.pre; + pos.pre.next = temp; + + pos.pre = temp; + temp.next = pos; + } + size++; + temp = null; + } + + @Override + public void clear() { + while(pollLast() != null){ + } + } + + @Override + public boolean contains(Object o) { + return indexOf(o) >= 0; + } + + @Override + public int indexOf(Object o) { + temp = head.next; + if(o == null){ + for(int i = 0; i < size; i++){ + if(temp.data == null){ + temp = null; + return i; + } + temp = temp.next; + } + }else{ + for(int i = 0; i < size; i++){ + if(o.equals(temp.data)){ + temp = null; + return i; + } + temp = temp.next; + } + } + return -1; + } + + @Override + public E get(int index) { + checkIndex(index); + + temp = head.next; + for(int i = 0; i < index; i++){ + temp = temp.next; + } + E obj = temp.data; + temp = null; + return obj; + } + + private void checkIndex(int index) { + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("Error index: " + index); + } + } + + @Override + public E remove(int index) { + checkIndex(index); + E obj = null; + if(size == 1){ + //链表中只有一个元素 + obj = last.data; + head.next = null; + last.pre = null; + last = null; + }else if(index == size - 1){ + //链表中有两个或更多的元素,但是移除下标为size()-1的元素 + obj = last.data; + + last = last.pre; + last.next.pre = null; + last.next = null; + }else{ + temp = head.next; + for(int i = 0; i < index; i++){ + temp = temp.next; + } + obj = temp.data; + + temp.pre.next = temp.next; + temp.next.pre = temp.pre; + temp.pre = null; + temp.next = null; + temp = null; + } + size--; + return obj; + } + + @Override + public boolean remove(Object o) { + int index = indexOf(o); + if(index >= 0){ + remove(index); + return true; + } + return false; + } + + @Override + public E set(int index, E element) { + checkIndex(index); + + temp = head.next; + for(int i = 0; i < index; i++){ + temp = temp.next; + } + E obj = temp.data; + temp.data = element; + temp = null; + return obj; + } + + @Override + public int size() { + return size; + } + + @Override + public Object[] toArray() { + Object[] arr = new Object[size]; + temp = head.next; + for(int i = 0; i < size; i++){ + arr[i] = temp.data; + temp = temp.next; + } + return arr; + } + + @Override + public Iterator iterator() { + return new Ite(); + } + + private class Ite implements Iterator{ + int pos; + int lastRet = -1; + + @Override + public boolean hasNext() { + return pos < size; + } + + @Override + public E next() { + if(pos == size){ + throw new NoSuchElementException(); + } + E element = get(pos); + lastRet = pos; + pos++; +// E element = get(lastRet = pos++); + return element; + } + + @Override + public void remove() { + if(lastRet == -1){ + throw new RuntimeException(); + } + LinkedList.this.remove(lastRet); + lastRet = -1; + } + + } + + private static final class Node{ + E data; + Node next; + Node pre; + } + + public void addFirst(E e){ + add(0, e); + } + + public void addLast(E e){ + add(size, e); + } + + public E removeFirst(){ + ensureElementExists(); + return remove(0); + + } + + + private void ensureElementExists() { + if(size == 0){ + throw new NoSuchElementException(); + } + } + + public E removeLast(){ + ensureElementExists(); + return remove(size - 1); + + } + + public E getFirst(){ + ensureElementExists(); + return get(0); + } + + public E getLast(){ + ensureElementExists(); + return get(size - 1); + + } + + public E pollFirst(){ + if(size == 0){ + return null; + } + return remove(0); + } + + public E pollLast(){ + if(size == 0){ + return null; + } + return remove(size - 1); + } + + public E peekFirst(){ + if(size == 0){ + return null; + } + return get(0); + } + + public E peekLast(){ + if(size == 0){ + return null; + } + return get(size - 1); + } + + + +} diff --git a/group13/1274639949/Exercise/src/lesson01/List.java b/group13/1274639949/Exercise/src/lesson01/List.java new file mode 100644 index 0000000000..d350a6e75f --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/List.java @@ -0,0 +1,85 @@ +package lesson01; + +public interface List { + + /** + * 在List的最后一个元素后添加一个元素 + * @param e 添加的元素 + */ + public boolean add(E e); + + /** + * 在List的index位置加入元素element + * @param index + * @param element + */ + public void add(int index, E element); + + /** + * 清空该List + */ + public void clear(); + + /** + * 判断List中是否含有对象o + * @param o + * @return 如果o存在于该List中则返回true, 否则返回false + */ + public boolean contains(Object o); + + /** + * 如果o存在于该List中,则返回它第一次出现的位置 + * 第一个元素的位置为0 + * 不存在时返回-1 + * @param o + * @return 返回o在List中的位置或-1 + */ + public int indexOf(Object o); + + /** + * 获取指定位置上的元素 + * @param index + * @return List中下标为index的元素 + */ + public E get(int index); + + /** + * 移除指定位置上的元素 + * @param index + * @return 被移除的元素。 + */ + public E remove(int index); + + /** + * 在List中移除指定的元素,如果存在多个,则只移除下标最小的那个 + * @param o + * @return 若指定元素被移除则返回true,否则返回false + */ + public boolean remove(Object o); + + /** + * 使用指定的元素替换指定位置上的元素。 + * @param index + * @param element + * @return 被替换掉的元素 + */ + public E set(int index, E element); + + /** + * 返回List中元素的个数 + * @return + */ + public int size(); + + /** + * 将List中的全部元素存放于一个数组中并返回该数组 + * @return + */ + public Object[] toArray(); + + /** + * 返回该List上的迭代器 + * @return + */ + public Iterator iterator(); +} diff --git a/group13/1274639949/Exercise/src/lesson01/Queue.java b/group13/1274639949/Exercise/src/lesson01/Queue.java new file mode 100644 index 0000000000..bfc51a417f --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/Queue.java @@ -0,0 +1,31 @@ +package lesson01; + +public class Queue { + + private LinkedList queue = new LinkedList(); + + /** + * 入列 + * @param e + */ + public void enQueue(E e){ + queue.addLast(e); + } + + /** + * 出列 + * @return + */ + public E deQueue(){ + return queue.pollFirst(); + } + + public boolean isEmpty(){ + return size() == 0; + } + + public int size(){ + return queue.size(); + } + +} diff --git a/group13/1274639949/Exercise/src/lesson01/Stack.java b/group13/1274639949/Exercise/src/lesson01/Stack.java new file mode 100644 index 0000000000..d820773f5f --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson01/Stack.java @@ -0,0 +1,37 @@ +package lesson01; + +import java.util.EmptyStackException; + +public class Stack{ + + private ArrayList stack = new ArrayList(); + + boolean isEmpty(){ + return size() == 0; + } + + E peek(){ + checkEmpty(); + return stack.get(size() - 1); + } + + E pop(){ + checkEmpty(); + return stack.remove(size() - 1); + } + + private void checkEmpty() { + if(isEmpty()){ + throw new EmptyStackException(); + } + } + + void push(E e){ + stack.add(e); + } + + public int size(){ + return stack.size(); + } + +} diff --git a/group13/1274639949/Exercise/src/lesson02/ArrayUtil.java b/group13/1274639949/Exercise/src/lesson02/ArrayUtil.java new file mode 100644 index 0000000000..92efc27086 --- /dev/null +++ b/group13/1274639949/Exercise/src/lesson02/ArrayUtil.java @@ -0,0 +1,235 @@ +package lesson02; + +import lesson01.ArrayList; +import lesson01.List; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + int len = origin.length; + int temp = 0; + for(int i = 0; i <= len >> 1; i++){ + temp = origin[i]; + origin[i] = origin[len - 1 - i]; + origin[len - 1 - i] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + public int[] removeZero(int[] oldArray){ + int count = 0; + for(int i = 0; i < oldArray.length; i++){ + if(oldArray[i] != 0) + count++; + } + + int[] arr = new int[count]; + + for(int i = oldArray.length - 1; i >= 0; i--){ + if(oldArray[i] != 0) + arr[--count] = oldArray[i]; + } + return arr; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + int pos1 = 0; + int pos2 = 0; + ArrayList al = new ArrayList<>(); + + while(pos1 < array1.length && pos2 < array2.length){ + if(array1[pos1] > array2[pos2]){ + al.add(array1[pos1]); + pos1++; + }else if(array1[pos1] < array2[pos2]){ + al.add(array2[pos2]); + pos2++; + }else{ + al.add(array1[pos1]); + pos1++; + pos2++; + } + } + + while(pos1 < array1.length){ + al.add(array1[pos1++]); + } + + while(pos2 < array2.length){ + al.add(array2[pos2++]); + } + + int[] arr = W2P(al.toArray(new Integer[0])); + + return arr; + } + + private int[] W2P(Integer[] array) { + int[] arr = new int[array.length]; + for(int i = 0; i < array.length; i++){ + arr[i] = array[i].intValue(); + } + return arr; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + int len = oldArray.length; + int[] newArr = new int[len + size]; +// for(int i = 0; i < len; i++){ +// newArr[i] = oldArray[i]; +// } + System.arraycopy(oldArray, 0, newArr, 0, len); + return newArr; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + if(max <= 0){ + throw new IllegalArgumentException("Error argument:" + max); + } + if(max == 1){ + return new int[0]; + }else{ + List list = new ArrayList<>(); + list.add(1); + list.add(1); + int count = 2; + int sum = 0; + + while((sum = list.get(count - 1) + list.get(count - 2)) <= max){ + list.add(sum); + count++; + } + return W2P((Integer[])list.toArray()); + } + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max < 2){ + throw new IllegalArgumentException("Illegal argument:" + max); + } + + List list = new ArrayList<>(); + + for(int i = 2; i <= max; i++){ + if(isPrimes(i)) + list.add(i); + } + + return W2P((Integer[])list.toArray()); + } + + private boolean isPrimes(int num) { + + for(int i = 0; i <= Math.sqrt(num); i++){ + if(num % i == 0){ + return false; + } + } + + return true; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + if(max < 0){ + throw new IllegalArgumentException(); + }else{ + List list = new ArrayList<>(); + list.add(0); + + for(int i = 0; i < max; i++){ + if(isPerfectNumber(i)){ + list.add(i); + } + } + + return W2P((Integer[])list.toArray()); + } + } + + private boolean isPerfectNumber(int num) { + int sum = 0; + + for(int i = 1; i <= Math.sqrt(num); i++){ + if(num % i == 0){ + sum += i; + sum += num/i; + } + } + + return sum == num; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + int len = array.length; + if(len == 0){ + return ""; + }else{ + StringBuilder sb = new StringBuilder(); + sb.append(array[0]); + for(int i = 1; i < len; i++){ + sb.append(seperator); + sb.append(array[i]); + } + return sb.toString(); + } + } + + +} diff --git a/group13/1274639949/lesson01/src/com/hans/ArrayList.java b/group13/1274639949/lesson01/src/com/hans/ArrayList.java deleted file mode 100644 index 3eeede5ce3..0000000000 --- a/group13/1274639949/lesson01/src/com/hans/ArrayList.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.hans; - -import java.util.Arrays; - -import javax.management.RuntimeErrorException; - -public class ArrayList implements List { - - private int size = 0;//ArrayListѾ洢ԪظҲһԪص±ꡣ - - private Object[] elementData = null; - - public ArrayList() { - elementData = new Object[3]; - } - - public ArrayList(int capacity){ - elementData = new Object[capacity]; - } - -// private static final final default - - /** - * oӵArrayListһԪصĺ - * @param o ӵԪ - */ - public void add(Object o){ - checkSize(); -// add(size++, o); - elementData[size++] = o; - } - - /** - * oӵָindexλ - * indexӦ index >= 0 && index <= size() Ϊ true - * @param index ӵλ - * @param o ӵԪ - */ - public void add(int index, Object o){ - if(index > size || index < 0){ - //sizeԪص±꣬indexsizeҲԡ - throw new ArrayIndexOutOfBoundsException("Index:" + index); - } - checkSize(); - System.arraycopy(elementData, index, elementData, index + 1, size - index); - elementData[index] = o; - size++; - } - - /** - * ȡindexλôԪ - * indexӦ index >= 0 && index < size() Ϊ true - */ - public Object get(int index){ - checkIndex(index); - return elementData[index]; - } - - /** - * ɾindexλôԪ - * indexӦ index >= 0 && index < size() Ϊ true - * @return ɾԪ - */ - public Object remove(int index){ - checkIndex(index); - Object obj = elementData[index]; - System.arraycopy(elementData, index + 1, elementData, index, size - index - 1); - size--; - return obj; - } - - /** - * ȡǰArrayListѾ洢Ԫصĸ - */ - public int size(){ - return this.size; - } - - /** - * ȡǰArrayListĵ - * @return ǰArrayListĵ - */ - public Iterator iterator(){ - return new Iterator(){ - private int count = 0; - - @Override - public boolean hasNext() { - return size > count; - } - - @Override - public Object next() { - if(count == size){ - throw new RuntimeErrorException(null, "ûиԪأ"); - } - return get(count++); - } - - @Override - public void remove() { - ArrayList.this.remove(count - 1); - } - - }; - } - - /** - * getremove±ǷԽ - * @param index ± - */ - private void checkIndex(int index){ - if(index >= size || index < 0){ - //sizeԪص±꣬index±ϻûд洢ݣ޷getremove - throw new ArrayIndexOutOfBoundsException("Index:" + index); - } - } - - /** - * ArrayListǷҪ - * ArrayListҪʱݣÿݽʹ20 - */ - private void checkSize(){ - if(size < elementData.length) return; - elementData = Arrays.copyOf(elementData, elementData.length + 20/*(int)(elementData.length * 1.2)*/); - } - -} diff --git a/group13/1274639949/lesson01/src/com/hans/BinaryTree.java b/group13/1274639949/lesson01/src/com/hans/BinaryTree.java deleted file mode 100644 index a4bf39dd3a..0000000000 --- a/group13/1274639949/lesson01/src/com/hans/BinaryTree.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.hans; - -public class BinaryTree { - BinaryTreeNode root = new BinaryTreeNode(); - - public boolean add(Object obj){ - - return true; - } -} diff --git a/group13/1274639949/lesson01/src/com/hans/LinkedList.java b/group13/1274639949/lesson01/src/com/hans/LinkedList.java deleted file mode 100644 index 8e2d421501..0000000000 --- a/group13/1274639949/lesson01/src/com/hans/LinkedList.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.hans; - -public class LinkedList implements List { - - private int size; - - private Node head; - - public LinkedList() { - head = new Node(); -// head.data = head; - } - - /** - * һԪ - */ - public void add(Object o){ - Node tail = getTail(); - - Node node = new Node(); - node.data = o; - - tail.next = node; - size++; - return; - } - - /** - * ָλüһԪ - * @param index ָλãӦ index > 0 && index <= size() Ϊ true - */ - public void add(int index , Object o){ - if(index < 0 || index > size) - throw new IndexOutOfBoundsException("Index:" + index); - - Node pos = head; - for(int i = 0; i < index; i++){ - //ҪindexλһԪأֻҪȡ index - 1 λõԪؼ - pos = pos.next; - } - Node node = new Node(); - node.data = o; - node.next = pos.next; - pos.next = node; - size++; - return; - } - - /** - * ȡָλôԪ - * @param index ҪȡԪصλãӦ index > 0 && index < size() Ϊ true - */ - public Object get(int index){ - checkIndex(index); - Node pos = head; - for(int i = 0; i <= index; i++){ - //Ϊ <= ,ΪҪȡindexλ - pos = pos.next; - } - return pos.data; - } - - /** - * ƳָλôԪ - * @param index ҪƳԪصλãӦ index > 0 && index < size() Ϊ true - */ - public Object remove(int index){ - checkIndex(index); - Node pos = head; - for(int i = 0; i < index; i++){ - pos = pos.next; - } - Node temp = pos.next; - pos.next = temp.next; - size--; - return temp.data; - } - - /** - * ȡ洢Ԫصĸ - */ - public int size(){ - return this.size; - } - - /** - * ڵһԪصǰһԪ - * @param o - */ - public void addFirst(Object o){ - add(0, o); - } - - /** - * һԪصĺһԪ - * @param o - */ - public void addLast(Object o){ - add(o); - } - - /** - * ƳһԪ - * @return ƳԪ - */ - public Object removeFirst(){ - return remove(0); - } - - /** - * ƳһԪ - * @return ƳԪ - */ - public Object removeLast(){ - return remove(size - 1); - } - - public Iterator iterator(){ - return null; - } - - - private static final class Node{ - Object data; - Node next; - } - - /** - * ȡһڵ - * @return - */ - private Node getTail(){ - Node tail = head; - while(tail.next != null){ - tail = tail.next; - } - return tail; - } - /** - * getremoveԪǷЧ - * @param index - */ - private void checkIndex(int index) { - if(index < 0 || index >= size) - throw new IndexOutOfBoundsException("Index:" + index); - } -} - diff --git "a/group13/1274639949/\346\214\207\344\273\244\346\274\253\346\270\270\350\256\260.md" "b/group13/1274639949/\346\214\207\344\273\244\346\274\253\346\270\270\350\256\260.md" deleted file mode 100644 index a89412cc01..0000000000 --- "a/group13/1274639949/\346\214\207\344\273\244\346\274\253\346\270\270\350\256\260.md" +++ /dev/null @@ -1 +0,0 @@ -如今计算机已经深入走进我们生活的方方面面,购物、娱乐、餐饮······,可以说我们无时无刻不在利用计算机给我们的 diff --git a/group13/2931408816/.idea/workspace.xml b/group13/2931408816/.idea/workspace.xml index 8e622af489..5491e4d0a1 100644 --- a/group13/2931408816/.idea/workspace.xml +++ b/group13/2931408816/.idea/workspace.xml @@ -58,34 +58,51 @@ + + + + + + + + + + + + + + + + + + + + - - - - - - + + + - - + + - - + + - - + + - - + + @@ -94,8 +111,8 @@ - - + + @@ -978,10 +995,10 @@ @@ -1337,7 +1359,7 @@ - + @@ -1544,124 +1566,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -1728,80 +1632,86 @@ - + - - + + - - + - - - + - - - + - - - - - - - - + + + + - @@ -2253,19 +2150,19 @@ - - - - - + + + + + - - - - + + + + @@ -2285,43 +2182,46 @@ + + + - + - + - + - + - + - + - + - + - + - + - @@ -2334,37 +2234,38 @@ + + + + + + + + + + + - - - - - - - - - - - - + + @@ -2398,6 +2299,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -2554,7 +2479,6 @@ - @@ -2566,14 +2490,7 @@ - - - - - - - - + @@ -2586,7 +2503,6 @@ - @@ -2602,7 +2518,6 @@ - @@ -2610,7 +2525,6 @@ - @@ -2636,7 +2550,6 @@ - @@ -2648,16 +2561,7 @@ - - - - - - - - - - + @@ -2670,94 +2574,119 @@ - - + + - - - - - + + - - + + + + + + + + + - - + - - - + + - + - - + + - - + - + - - + + + + + + + + + + + + + - + - - - - - + + + + + + + + + + - - + + - + - - + + - + - - + + + + + + + + + + diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/DownloadThread.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/DownloadThread.java index 3547f60826..f0e9feb78b 100644 --- a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/DownloadThread.java +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/DownloadThread.java @@ -7,13 +7,13 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; +import java.util.Arrays; public class DownloadThread extends Thread{ private Connection conn; private int startPos; private int endPos; - private RandomAccessFile raf = null; public DownloadThread( Connection conn, int startPos, int endPos){ @@ -24,19 +24,25 @@ public DownloadThread( Connection conn, int startPos, int endPos){ public void run(){ try { byte[] bytes = conn.read(startPos,endPos); - raf.write(bytes); - System.out.println("startPos = "+startPos+", "+"endPos = "+endPos); + LogUtil.log(" startPos = "+startPos+", "+"endPos = "+endPos); + writeToFile(bytes); } catch (IOException e) { e.printStackTrace(); } } - public void setFile(File file){ + private void writeToFile(byte[] bytes){ + File file = FileUtil.getFile(); try { - raf = new RandomAccessFile(file, "rws"); + RandomAccessFile raf = new RandomAccessFile(file, "rw"); + LogUtil.log("写入文件"); raf.seek(startPos); + raf.write(bytes); + raf.close(); + LogUtil.log("\n"+Arrays.toString(bytes)); } catch (IOException e) { e.printStackTrace(); } + } } diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileDownloader.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileDownloader.java index bd4897e750..1e80c3db79 100644 --- a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileDownloader.java +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileDownloader.java @@ -11,9 +11,11 @@ import java.io.IOException; import java.io.RandomAccessFile; import java.net.HttpURLConnection; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; public class FileDownloader { - private int threadNum = 4; + private int threadNum = 1; String url; @@ -51,23 +53,33 @@ public void execute(){ if (length < 0){ throw new ConnectionException(); } - File file =getFile(length); + threadNum = length / 1024; System.out.println("length = "+length); + FileUtil.setFile(url,length); int part = length/threadNum; + ExecutorService exe = Executors.newFixedThreadPool(threadNum); for (int i = 0; i < threadNum; i++) { DownloadThread thread; if (i==threadNum-1){ - thread = new DownloadThread(conn,i*part,length); + thread = new DownloadThread(conn,i*part,length-1); }else { thread = new DownloadThread(conn,i*part,(i+1)*part); } - thread.setFile(file); - thread.start(); + exe.execute(thread); } - listener.notifyFinished(); - } catch (ConnectionException e) { + exe.shutdown(); + while (true) { + if (exe.isTerminated()) { + System.out.println("结束了!"); + listener.notifyFinished(); + break; + } + System.out.println("休眠"); + Thread.sleep(200); + } + } catch (ConnectionException | InterruptedException e) { e.printStackTrace(); - }finally{ + } finally{ if(conn != null){ conn.close(); } @@ -82,8 +94,6 @@ public void setListener(DownloadListener listener) { this.listener = listener; } - - public void setConnectionManager(ConnectionManager ucm){ this.cm = ucm; } @@ -92,36 +102,4 @@ public DownloadListener getListener(){ return this.listener; } - private String getFileName(String url){ - int index = url.lastIndexOf("/"); - if (index<0){ - return "temp"; - } - String filename = url.substring(index+1); - if (filename.equals("")){ - return "temp"; - }else { - return filename; - } - } - private File getFile(int totalLen){ - File dir = new File("D:/Download/test"); - if(!dir.exists()){ - dir.mkdirs(); - } - File file = new File(dir, getFileName(url)); - RandomAccessFile raf = null; - try { - raf = new RandomAccessFile(file, "rws"); - System.out.println("totalLen = "+ totalLen); - if (totalLen < 0){ - throw new ConnectionException(); - } - raf.setLength(totalLen); - raf.close(); - } catch (ConnectionException | IOException e) { - e.printStackTrace(); - } - return file; - } } diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileUtil.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileUtil.java new file mode 100644 index 0000000000..6a6b4859da --- /dev/null +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/FileUtil.java @@ -0,0 +1,54 @@ +package cn.net.pikachu.download; + +import cn.net.pikachu.download.api.ConnectionException; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * Created by pikachu on 2017/3/13. + */ +public class FileUtil { + private static String filename = "temp"; + private static String url = null; + public static File getFile() { + return new File(filename); + } + public static void setFile(String url,int totalLen){ + + File dir = new File("D:/Download/test"); + if(!dir.exists()){ + dir.mkdirs(); + } + File file = new File(dir, getFileName(url)); + if (file.exists()){ + file.delete(); + } + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(file, "rws"); + System.out.println("totalLen = "+ totalLen); + if (totalLen < 0){ + throw new ConnectionException(); + } + raf.setLength(totalLen); + raf.close(); + filename=file.getCanonicalPath(); + } catch (ConnectionException | IOException e) { + e.printStackTrace(); + } + } + private static String getFileName(String url){ + int index = url.lastIndexOf("/"); + if (index<0){ + return "temp"; + } + String filename = url.substring(index+1); + if (filename.equals("")){ + return "temp"; + }else { + return filename; + } + } +} diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/LogUtil.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/LogUtil.java new file mode 100644 index 0000000000..a0a5b98c39 --- /dev/null +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/LogUtil.java @@ -0,0 +1,10 @@ +package cn.net.pikachu.download; + +/** + * Created by pikachu on 2017/3/14. + */ +public class LogUtil { + public static void log(String log){ + System.out.println(Thread.currentThread().getId()+"-"+Thread.currentThread().getName()+" "+log); + } +} diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionImpl.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionImpl.java index 235e64438a..75c1e325f8 100644 --- a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionImpl.java +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionImpl.java @@ -1,5 +1,6 @@ package cn.net.pikachu.download.impl; +import cn.net.pikachu.download.LogUtil; import cn.net.pikachu.download.api.Connection; import java.io.IOException; @@ -10,38 +11,62 @@ public class ConnectionImpl implements Connection { - private URL url; + private String url; private InputStream is; - private int totalReceived = 0; - public ConnectionImpl(URL url) { + + public ConnectionImpl(String url) { this.url = url; } @Override public byte[] read(int startPos, int endPos) throws IOException { - System.out.println("startPos = "+startPos+", endPos = "+endPos); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + URL u = new URL(url); + HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setConnectTimeout(5000); connection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); - is = connection.getInputStream(); - int len = endPos-startPos; - byte[] bytes = new byte[len]; - while (is.available()>0){ - System.out.println("available = "+is.available()); + InputStream is = connection.getInputStream(); + int len = endPos-startPos+1; + LogUtil.log(" startPos = "+startPos+", endPos = "+endPos+", len = "+len); + byte[] bytes = new byte[is.available()>len?is.available():len]; + int totalReceived = 0; + LogUtil.log("len = "+len+", available = "+is.available()); + int received = 0; + try { int left = len - totalReceived; - System.out.println("len - totalReceived = " + left); - int received; - if (left >= 1024){ - received = is.read(bytes,totalReceived,1024); - }else { - received = is.read(bytes,totalReceived,left); - } - System.out.println("received = "+received); - totalReceived+=received; - if (received == 0){ - break; + while (left > 0){ + LogUtil.log(" available = "+is.available()); + LogUtil.log(" left = " + left+", totalReceived = "+totalReceived+", len = "+len); + if (left >= 1024){ + received = is.read(bytes,totalReceived,1024); + }else { + received = is.read(bytes,totalReceived,left); + } + totalReceived+=received; + LogUtil.log(" received = "+received+", totalReceived = "+totalReceived); + + if (is.available() == 0){ + LogUtil.log("is.available() == 0"); + break; + } + if (received==0){ + LogUtil.log("received == 0"); + System.exit(0); + } + left = len - totalReceived; + /* + if (left == 0){ + LogUtil.log("left = 0; break;"); + break; + } + */ } + + }catch (Exception e){ + e.printStackTrace(); + LogUtil.log("Exception received = "+received+", totalReceived = "+totalReceived); + System.exit(0); } + return bytes; } @@ -50,13 +75,15 @@ public int getContentLength() { HttpURLConnection connection = null; try { - connection = (HttpURLConnection) url.openConnection(); + URL u = new URL(url); + connection = (HttpURLConnection) u.openConnection(); connection.setConnectTimeout(5000); + connection.setRequestMethod("GET"); return connection.getContentLength(); } catch (IOException e) { e.printStackTrace(); + return -1; } - return -1; } @Override @@ -69,5 +96,4 @@ public void close() { } } } - } diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionManagerImpl.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionManagerImpl.java index 1eb399d32d..8115e88b34 100644 --- a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionManagerImpl.java +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/ConnectionManagerImpl.java @@ -22,13 +22,6 @@ public class ConnectionManagerImpl implements ConnectionManager { @Override public Connection open(String url) throws ConnectionException { - URL u; - try { - u = new URL(url); - } catch (java.io.IOException e) { - e.printStackTrace(); - throw new ConnectionException(); - } - return new ConnectionImpl(u); + return new ConnectionImpl(url); } } diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadFileWithThreadPool.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadFileWithThreadPool.java new file mode 100644 index 0000000000..18e279d564 --- /dev/null +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadFileWithThreadPool.java @@ -0,0 +1,47 @@ +package cn.net.pikachu.download.impl.test; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * Created by pikachu on 2017/3/13. + */ +public class DownloadFileWithThreadPool { + public void getFileWithThreadPool(String urlLocation, String filePath, int poolLength) throws IOException { + Executor threadPool = Executors.newFixedThreadPool(poolLength); + + long len = getContentLength(urlLocation); + for (int i = 0; i < poolLength; i++) { + long start = i * len / poolLength; + long end = (i + 1) * len / poolLength - 1; + if (i == poolLength - 1) { + end = len; + } + DownloadWithRange download = new DownloadWithRange(urlLocation, filePath, start, end); + threadPool.execute(download); + } + + } + + public static long getContentLength(String urlLocation) throws IOException { + URL url = null; + if (urlLocation != null) { + url = new URL(urlLocation); + } + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setReadTimeout(5000); + conn.setRequestMethod("GET"); + long len = conn.getContentLength(); + + return len; + } + + public static void main(String[] args) throws IOException { +// String url = "http://localhost:8080/mybatis-jpetstore-6.0.0/actions/Catalog.action"; + String url = "http://yydl.duowan.com/4/setup/YYSetup-8.20.0.1-zh-CN.exe"; + new DownloadFileWithThreadPool().getFileWithThreadPool(url,"D:/Download/test/yy.exe",1000); + } +} \ No newline at end of file diff --git a/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadWithRange.java b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadWithRange.java new file mode 100644 index 0000000000..a1402524be --- /dev/null +++ b/group13/2931408816/lesson3/src/main/java/cn/net/pikachu/download/impl/test/DownloadWithRange.java @@ -0,0 +1,80 @@ +package cn.net.pikachu.download.impl.test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * Created by pikachu on 2017/3/13. + */ +public class DownloadWithRange implements Runnable +{ + private String urlLocation; + + private String filePath; + + private long start; + + private long end; + + DownloadWithRange(String urlLocation, String filePath, long start, long end) + { + this.urlLocation = urlLocation; + this.filePath = filePath; + this.start = start; + this.end = end; + } + + @Override + public void run() + { + try + { + HttpURLConnection conn = getHttp(); + conn.setRequestProperty("Range", "bytes=" + start + "-" + end); + + File file = new File(filePath); + RandomAccessFile out = null; + if (file != null) + { + out = new RandomAccessFile(file, "rwd"); + } + out.seek(start); + InputStream in = conn.getInputStream(); + System.out.println(in.available()+" "+(end-start)); + byte[] b = new byte[1024]; + int len = 0; + while ((len = in.read(b)) != -1) + { + out.write(b, 0, len); + } + in.close(); + out.close(); + } + catch (Exception e) + { + e.getMessage(); + } + + } + + public HttpURLConnection getHttp() throws IOException + { + URL url = null; + if (urlLocation != null) + { + url = new URL(urlLocation); + } + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setReadTimeout(5000); + conn.setRequestMethod("GET"); + + return conn; + } + +} \ No newline at end of file diff --git a/group13/2931408816/lesson3/src/main/kotlin/main.kt b/group13/2931408816/lesson3/src/main/kotlin/main.kt new file mode 100644 index 0000000000..a9d905cab4 --- /dev/null +++ b/group13/2931408816/lesson3/src/main/kotlin/main.kt @@ -0,0 +1,40 @@ +import java.io.File +import java.io.PrintWriter +import java.nio.file.Files +import java.nio.file.Paths + +/** + * Created by pikachu on 2017/3/13. + */ + +fun main(args: Array) { + val dir = File("E:/users/pikachu/documents/Tencent Files/2931408816/FileRecv/treat/Input") + dir.listFiles().forEach { + if (!it.isDirectory){ + + println(it.canonicalPath) + println(it.absolutePath) + println(it.parent) + val dir = File("${it.parent}/temp") + if (!dir.exists()){ + dir.mkdirs() + } + val file = File(dir,it.name) + if (!file.exists()){ + file.createNewFile() + } + val out = PrintWriter(file) + val stream = Files.newInputStream(Paths.get(it.canonicalPath)) + stream.buffered().use { + while (it.available()>0){ + out.print(it.read().toChar()) + if(it.available()>0){ + out.print(" ") + } + } + } + + out.close() + } + } +} \ No newline at end of file diff --git a/group13/2931408816/lesson3/src/test/java/cn/net/pikachu/download/FileDownloaderTest.java b/group13/2931408816/lesson3/src/test/java/cn/net/pikachu/download/FileDownloaderTest.java index 5bbda22795..a01cb4ce5a 100644 --- a/group13/2931408816/lesson3/src/test/java/cn/net/pikachu/download/FileDownloaderTest.java +++ b/group13/2931408816/lesson3/src/test/java/cn/net/pikachu/download/FileDownloaderTest.java @@ -23,20 +23,23 @@ public void testDownload() { // String url = "http://localhost:8080/test.jpg"; - String url = "http://n1.itc.cn/img8/wb/recom/2016/07/26/146946506808699302.JPEG"; +// String url = "http://n1.itc.cn/img8/wb/recom/2016/07/26/146946506808699302.JPEG"; + +// String url = "http://localhost:8080/mybatis-jpetstore-6.0.0/"; +// String url = "http://www.cnblogs.com/iwideal/p/6045118.html"; +// String url = "http://localhost:8080/mybatis-jpetstore-6.0.0/actions/Catalog.action"; +// String url = "http://blog.csdn.net/cnhk1225/article/details/34429317"; +// String url = "http://rel.huya.com/apk/live.apk"; +// String url = "http://yydl.duowan.com/4/setup/YYSetup-8.20.0.1-zh-CN.exe"; +// String url = "https://discuss.kotlinlang.org/t/kotlin-1-1-language-reference-as-anki-https-apps-ankiweb-net-deck/2324"; + String url = "http://qtdream.com/"; FileDownloader downloader = new FileDownloader(url); ConnectionManager cm = new ConnectionManagerImpl(); downloader.setConnectionManager(cm); - downloader.setListener(new DownloadListener() { - @Override - public void notifyFinished() { - downloadFinished = true; - } - - }); + downloader.setListener(() -> downloadFinished = true); downloader.execute(); @@ -44,7 +47,7 @@ public void notifyFinished() { // 等待多线程下载程序执行完毕 while (!downloadFinished) { try { - System.out.println("还没有下载完成,休眠五秒"); + System.out.println(""); System.out.println("None"); //休眠5秒 Thread.sleep(5000); @@ -52,7 +55,6 @@ public void notifyFinished() { e.printStackTrace(); } } - System.out.println("下载完成!"); System.out.println("Done!"); diff --git a/group13/453070251/lessones01/LinkedList$Iter.class b/group13/453070251/lessones01/LinkedList$Iter.class new file mode 100644 index 0000000000..e23fa5e756 Binary files /dev/null and b/group13/453070251/lessones01/LinkedList$Iter.class differ diff --git a/group13/453070251/lessones01/LinkedList.class b/group13/453070251/lessones01/LinkedList.class index bc2967d2b8..dac217bee7 100644 Binary files a/group13/453070251/lessones01/LinkedList.class and b/group13/453070251/lessones01/LinkedList.class differ diff --git a/group13/453070251/lessones01/LinkedList.java b/group13/453070251/lessones01/LinkedList.java index 5c85dba646..b979d17bfc 100644 --- a/group13/453070251/lessones01/LinkedList.java +++ b/group13/453070251/lessones01/LinkedList.java @@ -1,6 +1,23 @@ package lessones01; import lessones01.Node; -public class LinkedList{ +import others.Range; +import java.util.Iterator; +public class LinkedList implements Iterable{ + private static class Iter implements Iterator{ + private Node node; + private LinkedList list; + public Iter(Node arg_nullNode,LinkedList arg_list){ + node = arg_nullNode; + list = arg_list; + } + public boolean hasNext(){ + return node.right!=null; + } + public E next(){ + node = node.right; + return node.value; + } + } public static void main(String[] args){ LinkedList arr = new LinkedList(); arr.add("0"); @@ -17,111 +34,180 @@ public static void main(String[] args){ arr.add("before 2",2); System.out.println(arr.get(2)); System.out.println(arr.get(4)); - arr.set(4,"4"); + arr.set("4",4); System.out.println(arr.get(4)); - arr.set(8,"8"); + arr.set("8",8); System.out.println(arr.get(8)); + arr.remove(5); + arr.remove(6); + for(String x:arr){ + System.out.print(x); + System.out.print(","); + } } - protected Node first; - protected Node lastest; + protected Node nullNode; + protected Node point; + protected int pointNum; protected int size; public LinkedList(){ - lastest = first = new Node(null); + nullNode = point = new Node(null); + pointNum = -1; size = 0; } - public T get(int arg_num){ - //throw Error if arg_num<0,unfinished - return _get(arg_num); + private void setPoint(int n){ + while(size<=n){add(null);} + if(n<0){ + point = nullNode; + pointNum = -1; + }else{ + if((n<<1) < pointNum){ + point = nullNode; + pointNum = -1; + } + while(pointNumn){ + point = point.left; + pointNum--; + } + } } - public void set(int arg_num,T arg_value){ - //throw Error if arg_num<0,unfinished - _set(arg_num,arg_value); + public int size(){ + return size; } - public T remove(int arg_num){ - //throw Error if arg_num<0,unfinished - return _remove(arg_num).value; + public void add(T arg_value){ + setPoint(size-1); + point.setRight(new Node(arg_value)); + size++; } public void add(T arg_value,int arg_num){ - //throw Error if arg_num<0,unfinished - _add(arg_value,arg_num); + if(arg_num<0){return;} + setPoint(arg_num-1); + Node temp = point.right; + point.setRight(new Node(arg_value)); + point.right.setRight(temp); + size++; } - public void add(T arg_value){ - _add(arg_value,size); + public void set(T arg_value,int arg_num){ + if(arg_num<0){return;} + setPoint(arg_num); + point.value = arg_value; } - public int size(){ - return size; - } - protected Node _remove(int arg_num){ - if(arg_num node = _getNode(arg_num); - node.remove(); - size--; - if(arg_num == size){ - lastest = node.left; - }else if(arg_num == 0 && size != 0){ - first = node.right; - } - return node; + public T get(int arg_num){ + if(size>arg_num&&arg_num>=0){ + setPoint(arg_num); + return point.value; }else{ return null; } } - protected Node _getNode(int arg_num){ - Node node = first; - for(int num = 0;num=size){return null;} + setPoint(arg_num-1); + T temp = point.right.value; + point.setRight(point.right.right); + size--; + return temp; } - protected T _get(int arg_num){ - if(arg_num>=size){return null;} - return _getNode(arg_num).value; + public void remove(int arg_num,int arg_length){ + Range r = new Range(0,size-1); + r.and(new Range(arg_num,arg_num+arg_length)); + setPoint(r.max()); + Node temp = point; + setPoint(r.min()-1); + point.setRight(temp); + size-=r.max()- r.min(); } - protected void _set(int arg_num,T arg_value){ - if(arg_num>=size){ - _add(arg_value,arg_num); + public Integer index(T arg_value){ + setPoint(-1); + if(arg_value == null){ + while(point.right != null){ + point = point.right; + pointNum++; + if(point.value == null){return pointNum;} + } }else{ - _getNode(arg_num).value = arg_value; + while(point.right != null){ + point = point.right; + pointNum++; + if(arg_value.equals(point.value)){return pointNum;} + } } + return null; } - protected void _add(T arg_value,int arg_num){ - if(arg_num > size){ - Node n = new Node(null); - lastest.setRight(n); - for(int num=size+1;num(null)); - n = n.right; - } - n.setRight(new Node(arg_value)); - lastest = n.right; - size = arg_num+1; - }else if(arg_num == size){ - if(size == 0){ - lastest.value = arg_value; + public void reverse(){ + if(size<2){return;} + setPoint(-1); + _reverse(); + pointNum = size - pointNum; + } + public void removeFirstHalf(){ + setPoint(size>>1); + nullNode.setRight(point); + size -= pointNum; + pointNum = 0; + } + public Iterator iterator(){ + return new Iter(nullNode,this); + } + public LinkedList getElements(LinkedList arg_list){ + LinkedList ret = new LinkedList(); + for(Integer x:arg_list){ret.add(get(x));} + return ret; + } + public void subtract(LinkedList arg_list){ + for(T x:arg_list){ + Integer i; + while((i = index(x))!=null){this.remove(i);} + } + } + public void removeDuplicateValues(){ + setPoint(0); + while(point.right != null){ + if(point.value.equals(point.right.value)){ + remove(pointNum+1); }else{ - lastest.setRight(new Node(arg_value)); - lastest = lastest.right; + setPoint(pointNum+1); } - size++; - }else if(arg_num == 0){ - first.setLeft(new Node(arg_value)); - first = first.left; - size++; - }else{ - Node node = _getNode(arg_num); - node.addLeft(new Node(arg_value)); - size++; } - } - protected Integer index(T o){ - Node n = _getNode(0); - if(o == null){ - for(int i=0;(n = n.right)!=null;i++){if(n.value == null){return i;}} - }else{ - for(int i=0;(n = n.right)!=null;i++){if(o.equals(n.value)){return i;}} + public > void removeRange(E min,E max){ + int length = 0; + int i = 0; + while(i=0; + if(bigThenMin&&lessThenMax){length++;} + if(bigThenMin&&!lessThenMax){break;} + i++; } - return null; + remove(i,length); + } + public > LinkedList intersection(LinkedList arg_list){ + LinkedList ret = new LinkedList(); + int x=0;int y = 0; + while(x0){ + x++; + }else{ + y++; + } + } + ret.removeDuplicateValues(); + return ret; + } + private void _reverse(){ + Node temp = point; + Node temp2 = (point = point.right); + if(temp == null){return;} + _reverse(); + temp2.setRight(temp); } } \ No newline at end of file diff --git a/group13/453070251/lessones02/ArrayUtil.class b/group13/453070251/lessones02/ArrayUtil.class index 9a7ca7bab0..13e31a1654 100644 Binary files a/group13/453070251/lessones02/ArrayUtil.class and b/group13/453070251/lessones02/ArrayUtil.class differ diff --git a/group13/453070251/lessones02/ArrayUtil.java b/group13/453070251/lessones02/ArrayUtil.java index f68830444b..c801fcf274 100644 --- a/group13/453070251/lessones02/ArrayUtil.java +++ b/group13/453070251/lessones02/ArrayUtil.java @@ -1,6 +1,6 @@ package lessones02; import others.PrimeGetter; -import others.LinkedListWithFloat; +import lessones01.LinkedList; public class ArrayUtil{ public static void reverseArray(int[] arg_arr){ for(int i = arg_arr.length/2;i>0;i--){ @@ -79,7 +79,7 @@ public static int[] getPrimes(int max){ } private static int[] two_s_TimesEnd = {8,6,2,4}; public static int[] getPerfectNumbers(int arg_num){ - LinkedListWithFloat arr = new LinkedListWithFloat(); + LinkedList arr = new LinkedList(); for(int i=2;;i++){ int z = (int)Math.pow(2,i) - 1; int zz = z*two_s_TimesEnd[i&3]; diff --git a/group13/453070251/lessones03/LinkedListNoPrior.class b/group13/453070251/lessones03/LinkedListNoPrior.class deleted file mode 100644 index 2c2e51d419..0000000000 Binary files a/group13/453070251/lessones03/LinkedListNoPrior.class and /dev/null differ diff --git a/group13/453070251/lessones03/LinkedListNoPrior.java b/group13/453070251/lessones03/LinkedListNoPrior.java deleted file mode 100644 index e26f1cd08e..0000000000 --- a/group13/453070251/lessones03/LinkedListNoPrior.java +++ /dev/null @@ -1,74 +0,0 @@ -package lessones03; -import lessones01.Node; -import lessones01.LinkedList; -import others.Range; -//ֻҪpriorͺ͵һ˰ɡ -//ȻҪǵбд벻ùǵ˫(LinkedList,Node) -public class LinkedListNoPrior extends LinkedList{ - protected void _reverse(){ - if(size() == 1){return;} - T temp = _remove(size()-1).value; - _reverse(); - _add(temp,0); - } - protected void _removeFirstHalf(){ - (first = _getNode((int)(size()>>1))).setLeft(null);//ڵҲsetLeft - size-=size/2; - } - protected void _remove(int arg_i,int arg_length){ - Range thisRange = new Range(0,size()); - Range targetRange = thisRange.and(new Range(arg_i,arg_i+arg_length)); - if(size == arg_length){ - (lastest = first).value = null; - first.setRight(null); - }else if(targetRange.min() == 0){ - first = _getNode(targetRange.max()); - first.setLeft(null); - }else if(targetRange.max() == size){ - lastest = _getNode(targetRange.min()-1); - lastest.setRight(null); - }else{ - _getNode(targetRange.min()-1).setRight(_getNode(targetRange.max())); - } - size -= arg_length; - //for(int i = targetRange.min();i arg_list){ - //ĿߵѾźLinkedList - //û´ĻӦþ취Żˡ - //ȻѾLinkedListWithFloat(Ц) - //Ȼﲻܼ̳LinkedListWithFloat - //ps:arg_listLinkedListWithFloat,ԲʲôŻ - int list_size = arg_list.size(); - T[] arr = (T[])(new Object[size()]); - int list_i = 0; - int i = arg_list.get(0/*list_i*/); - Node node = _getNode(i); - while((node!=null)&&list_i arg_list){ - for(int i=0;i extends LinkedListNoPrior{ - public static void main(String[] args){ - LinkedListWithFloat arr = new LinkedListWithFloat(); - arr.add("0"); - System.out.println(arr.get(0)); - arr.add("1"); - System.out.println(arr.get(1)); - - System.out.println(arr.get(3)); - arr.add("3",3); - System.out.println(arr.get(3)); - arr.add("before 2",2); - System.out.println(arr.get(2)); - System.out.println(arr.get(4)); - arr.set(4,"4"); - System.out.println(arr.get(4)); - arr.set(8,"8"); - System.out.println(arr.get(8)); - System.out.println(arr.remove(8)); - System.out.println(arr.get(8)); - System.out.println(arr.remove(2)); - System.out.println(arr.get(2)); - System.out.println(arr.remove(0)); - System.out.println(arr.get(0)); - System.out.println(arr.size()); - } - - private Node floatNode; - private int floatNum; - public LinkedListWithFloat(){ - super(); - floatNode = first; - floatNum = 0; - } - protected Node _getNode(int arg_num){ - int position = arg_num - floatNum; - if(position == 0){return floatNode;} - //arg_num = (int leftPosition = arg_num); - int rightPosition = size() - 1 - arg_num; - boolean floatNear = position * position <= arg_num * rightPosition; - if(floatNear){ - if(position>0){ - return findFloatRight(arg_num); - }else/*if(position<0)*/{ - return findFloatLeft(arg_num); - } - }else if(position<0){ - floatNode = first; - floatNum = 0; - return findFloatRight(arg_num); - }else/*if(position>0)*/{ - floatNode = lastest; - floatNum = rightPosition + arg_num;//size()-1 - return findFloatLeft(arg_num); - } - } - protected void _add(T arg_value,int arg_num){ - super._add(arg_value,arg_num); - if(arg_num <= floatNum){floatNum++;} - } - protected Node _remove(int arg_num){ - Node temp = super._remove(arg_num); - if(temp == null){return temp;} - if(temp.right != null){ - floatNode = temp.right; - }else{ - floatNode = lastest; - floatNum = size()-1; - } - return temp; - } - protected void _removeFirstHalf(){ - super._removeFirstHalf(); - floatNode = first; - floatNum = 0; - } - private Node findFloatLeft(int arg_num){ - for(;floatNum>arg_num;){ - floatNode = floatNode.left; - floatNum--; - } - return floatNode; - } - private Node findFloatRight(int arg_num){ - for(;floatNum primes = new LinkedListWithFloat(); + private static LinkedList primes = new LinkedList(); public static int get(int arg_num){ for(int i = primes.size()-1;i + + + + + + diff --git a/group17/102228177/work3_5/.project b/group17/102228177/work3_5/.project new file mode 100644 index 0000000000..381fe45b69 --- /dev/null +++ b/group17/102228177/work3_5/.project @@ -0,0 +1,17 @@ + + + work3_5 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group17/102228177/work3_5/.settings/org.eclipse.jdt.core.prefs b/group17/102228177/work3_5/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..7341ab1683 --- /dev/null +++ b/group17/102228177/work3_5/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/group17/102228177/work3_5/src/com/coderising/data/LinkedList.java b/group17/102228177/work3_5/src/com/coderising/data/LinkedList.java new file mode 100644 index 0000000000..22a72affaf --- /dev/null +++ b/group17/102228177/work3_5/src/com/coderising/data/LinkedList.java @@ -0,0 +1,366 @@ +package com.coderising.data; + + +import java.util.Arrays; +import java.util.NoSuchElementException; + +public class LinkedList implements List { + + private Node head; + private int size; + + public LinkedList(){ + size = 0; + head = null; + } + + public void add(Object o){ + Node node = new Node(o); + if(head == null){ + head = node; + }else{ + //p为游标 从头遍历到尾 + Node p = head; + while(p.next != null){ + p = p.next; + } + p.next = node; + } + size++; + } + + public void add(int index , Object o){ + //判断不为空链表 + if(head != null){ + Node p = head; + int k = 0; + //扫描单链表查找第index-1个节点 + while(k < index-1 && p.next != null){ + k++; + p = p.next; + } + //判断是否找到第index-1个节点 + if(p != null){ + Node node = new Node(o); + node.next = p.next; + p.next = node; + } + size++; + } + } + + public Object get(int index){ + if(index <0 || index >= size){ + throw new IndexOutOfBoundsException(); + }else{ + Node p = head; + int k = 0; + while(k < index && p.next != null){ + k++; + p = p.next; + } + return p.data; + } + } + public Object remove(int index){ + if(index <0 || index >= size){ + throw new IndexOutOfBoundsException(); + }else{ + if(head != null){ + int k = 0; + Node p = head; + while(k < index-1 && p!=null){ + k++; + p = p.next; + } + Node pn = p.next; + if(pn != null){ + p.next = pn.next; + size--; + return pn.data; + } + } + } + return null; + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + Node node = new Node(o); + node.next = head; + head = node; + size++; + } + + public void addLast(Object o){ + Node node = new Node(o); + if(head == null){ + head = node; + }else{ + Node p = head; + while(p.next != null){ + p = p.next; + } + p.next = node; + } + size++; + } + + public Object removeFirst(){ + if(head == null){ + throw new NoSuchElementException(); + } + Node node = head; + head = node.next; + size--; + return node.data; + } + public Object removeLast(){ + if(head == null){ + throw new NoSuchElementException(); + }else{ + Node p = head; + int k = 0; + while(k < size-1 && p.next != null){ + k++; + p = p.next; + } + Node last = p.next; + p.next = null; + size--; + return last.data; + } + } + + private static class Node{ + Object data; + Node next; + private Node(Object o){ + this.data = o; + this.next = null; + } + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if(null == head || null == head.next){ + return; + } + else{ + Node pre = head; + Node cur = head.next; + Node next; + while(cur != null){ + next = cur.next; + cur.next = pre; + pre = cur; + cur = next; + } + head.next = null; + head = pre; + } + } + + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf(){ + int num = size/2; + for (int i = 0; i < num; i++) { + removeFirst(); + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + if(i <0 || i >= size){ + throw new IndexOutOfBoundsException(); + }else{ + int len = size-i>=length ? length :size-i; + int k = 0; + while(k < len){ + remove(i); + k++; + } + } + } + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + int[] arr = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + arr[i] = (int) this.get((int) list.get(i)); + } + return arr; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + + public void subtract(LinkedList list){ + for (int i = 0; i < list.size(); i++) { + this.remove(list.get(i)); + } + } + + /** + * 传入数据删除节点 + * @param obj + */ + public void remove(Object obj){ + if(head==null){ + throw new RuntimeException("LinkedList is empty!"); + } + //如果要删除的结点是第一个,则把下一个结点赋值给第一个结点 + if(head.data==obj){ + head=head.next; + size--; + }else{ + Node pre=head; //上一节点 + Node cur=head.next; //当前结点 + while(cur!=null){ + if(cur.data.equals(obj)){ + pre.next=cur.next; + size--; + } + pre=pre.next; + cur=cur.next; + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + if(head == null){ + throw new RuntimeException("LinkedList is empty!"); + }else{ + Node pre = head; + Node cur = head; + while(cur.next != null){ + cur = cur.next; + Object data = pre.data; + while(cur.data == data){ + if(cur.next == null){ + pre.next = null; + break; + } + pre.next = cur.next; + size--; + cur =cur.next; + if(cur == null){ + break; + } + } + pre = pre.next; + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + if(head == null){ + throw new RuntimeException("LinkedList is empty!"); + }else{ + Node q = head; + //头判断 + if((int)q.data>min && (int)q.datamin && (int)p.data + + + + + diff --git a/group17/333333/.gitignore b/group17/333333/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group17/333333/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group17/333333/.project b/group17/333333/.project new file mode 100644 index 0000000000..4b0233c4cc --- /dev/null +++ b/group17/333333/.project @@ -0,0 +1,17 @@ + + + 333 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group17/365689789/.classpath b/group17/365689789/.classpath new file mode 100644 index 0000000000..d171cd4c12 --- /dev/null +++ b/group17/365689789/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/group17/365689789/.gitignore b/group17/365689789/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group17/365689789/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group17/365689789/.project b/group17/365689789/.project new file mode 100644 index 0000000000..3e0116edb8 --- /dev/null +++ b/group17/365689789/.project @@ -0,0 +1,17 @@ + + + L365689789 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group17/article/20170305-20170312.md b/group17/article/20170305-20170312.md index b46d00b2c0..f43f5b5fb2 100644 --- a/group17/article/20170305-20170312.md +++ b/group17/article/20170305-20170312.md @@ -12,7 +12,7 @@ 1204187480 -102228177 +102228177 http://note.youdao.com/noteshare?id=eaa0a94d3cafd12a73315a24ea68e569 876385982 diff --git a/group18/1159828430/20160305/.classpath b/group18/1159828430/20160305/.classpath new file mode 100644 index 0000000000..3e0fb272a8 --- /dev/null +++ b/group18/1159828430/20160305/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/group18/1159828430/20160305/.gitignore b/group18/1159828430/20160305/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group18/1159828430/20160305/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group18/1159828430/20160305/.project b/group18/1159828430/20160305/.project new file mode 100644 index 0000000000..343a59edbc --- /dev/null +++ b/group18/1159828430/20160305/.project @@ -0,0 +1,17 @@ + + + 20160305 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group18/1159828430/20160305/src/com/coding/basic/LinkedList.java b/group18/1159828430/20160305/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..ef3f794cd5 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/basic/LinkedList.java @@ -0,0 +1,373 @@ +package com.coding.basic; + +import java.util.Iterator; + +/** + * @author Scholar + * @Time:2017年3月6日 下午9:45:54 + * @version 1.0 + */ +public class LinkedList implements List { + + private Node head; + private int size; + + public boolean add(Object o){ + addLast(o); + return true; + + } + public void add(int index , Object o){ + checkPositionIndex(index); + if (index == 0) { + addFirst(o); + } else if (index == size) { + addLast(o); + } else { + Node x = head; + for (int i = 0; i < index - 2; i++) { + x = x.next; + } + Node temp = new Node(o,x.next); + x.next = temp; + } + size++; + } + public Object get(int index){ + checkElementIndex(index); + Node x = head; + for (int i = 0; i < index; i++) { + x = x.next; + } + return x.data; + } + @SuppressWarnings("unused") + public Object remove(int index){ + checkElementIndex(index); + Object element = null; + if (index == 0) { + Node removeNode = head; + head = head.next; + element = removeNode.data; + removeNode = null; + } else { + checkElementIndex(index - 1); + Node x = head; + for (int i = 0; i < index - 1; i++) { + x = x.next; + } + Node removeNode = x.next; + x.next = removeNode.next; + element = removeNode.data; + removeNode = null; + } + size--; + return element; + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + Node temp = head; + Node newNode = new Node(o,temp); + head = newNode; + size++; + } + public void addLast(Object o){ + Node temp = new Node(o, null); + if (size == 0) { + head = temp; + } else { + Node x = head; + while (x.next != null) { + x = x.next; + } + x.next = temp; + } + size++; + } + public Object removeFirst(){ + Object element = null; + if (size != 0) { + element = head.data; + head.data = null; + + Node next = head.next; + head.next = null; + head = next; + size--; + } + return element; + } + public Object removeLast(){ + Object element = null; + if (size != 0) { + if (head.next == null) { + element = head.data; + head.data = null; + } else { + Node x = head; + for (int i = 0; i < size - 2; i++) { + x = x.next; + } + Node removeNode = x.next; + x.next = null; + element = removeNode.data; + removeNode = null; + } + size--; + } + return element; + } + public Iterator iterator(){ + return new LinkedListIterator(); + } + + //检查下标是否合法 + private void checkElementIndex(int index){ + if (!isElementIndex(index)) { + throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); + } + } + + @SuppressWarnings("unused") + private void checkPositionIndex(int index){ + if (!isPositionIndex(index)) { + throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); + } + } + + //检查该参数是否为现有元素的索引。 + private boolean isElementIndex(int index) { + return index >= 0 && index < size; + } + + //检查参数是否是迭代器或添加操作的有效位置的索引 + private boolean isPositionIndex(int index) { + return index >= 0 && index <= size; + } + + @SuppressWarnings("unused") + private static class Node{ + Object data; + Node next; + Node(Object data, Node next){ + this.data = data; + this.next = next; + } + } + + private class LinkedListIterator implements Iterator{ + + private Node currentNode = head; + private int nextIndex = 0;//参考源码中的写法 + + @Override + public Object next() { + + Object data = currentNode.data; + currentNode = currentNode.next; + nextIndex ++; + return data; + } + + @Override + public boolean hasNext() { + return nextIndex != size; + } + + } + + + + + + + + + + + + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if (head!=null) { + //上一结点 + Node pre=head; + + //当前结点 + Node cur=head.next; + + //用于存储下一节点 + Node tem; + + //cur==null 即尾结点 + while(cur!=null){ + + //下一节点存入临时结点 + tem=cur.next; + + //将当前结点指针指向上一节点 + cur.next = pre; + + //移动指针 + pre=cur; + cur=tem; + } + head.next = null; + } + + + //reverse(head); + } + private Node reverse(Node first) { + // first看作是前一结点,first.next是当前结点,reHead是反转后新链表的头结点 + if (first == null || first.next == null) { + return head;// 若为空链或者当前结点在尾结点,则直接还回 + } + Node reHead = reverse(first.next);// 先反转后续节点head.getNext() + first.next.next = first;// 将当前结点的指针域指向前一结点 + first.next = null;// 前一结点的指针域令为null; + return reHead;// 反转后新链表的头结点 + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf(){ + int removeLength = size()/2; + for (int i = 0; i < removeLength; i++) { + removeFirst(); + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int index, int length){ + for (int i = 0; i < length; i++) { + this.remove(index); + } + + } + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + int[] result = new int[list.size()]; + Iterator iterator = list.iterator(); + int offset = 0; + while (iterator.hasNext()) { + int temp = (int) this.get((int)iterator.next()); + result[offset++] = temp; + } + return result; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + + public void subtract(LinkedList list){ + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + int temp = (int) iterator.next(); + Node x = head; + Node p = null; + while (x.next != null) { + if ((int)x.data > temp) { + break; + } + if((int)x.data == temp){ + if (p == null) { + removeFirst(); + x = head; + } else { + p.next = x.next; + } + } + p = x; + x = x.next; + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + Node p = head; + while(p.next != null){ + Node x = p; + while (x.next != null) { + if(x.next.data == p.data){ + x.next=x.next.next; + } + x=x.next; + } + p = p.next; + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + Node p = head; + int i = (int)p.data; + if (i > min && i < max) { + while ((int)p.data > min) { + if ((int)p.data >= max) { + break; + } + removeFirst(); + p = head; + } + } else { + while (p.next != null) { + int temp = (int) p.next.data; + if (temp >= max) { + break; + } + if (temp > min) { + p.next=p.next.next; + } + p = p.next; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + + + + + + return null; + } +} \ No newline at end of file diff --git a/group18/1159828430/20160305/src/com/coding/basic/List.java b/group18/1159828430/20160305/src/com/coding/basic/List.java new file mode 100644 index 0000000000..bf225b281f --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/basic/List.java @@ -0,0 +1,13 @@ +package com.coding.basic; +/** + * @author Scholar + * @Time:2017年2月20日 下午8:52:08 + * @version 1.0 + */ +public interface List { + public boolean add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} \ No newline at end of file diff --git a/group18/1159828430/20160305/src/com/coding/basic/TestLinkedList.java b/group18/1159828430/20160305/src/com/coding/basic/TestLinkedList.java new file mode 100644 index 0000000000..d78a3437fc --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/basic/TestLinkedList.java @@ -0,0 +1,143 @@ +package com.coding.basic; + +import org.junit.Before; +import org.junit.Test; + +/** + * @author 李兵兵 + * @Time:2017年3月12日 上午11:02:54 + * @version 1.0 + */ +public class TestLinkedList { + private LinkedList list; + @Before + public void beforeTest() { + list = new LinkedList(); + list.add(5); + list.add(6); + list.add(7); + list.add(8); + list.add(9); + list.add(10); + list.add(11); + //list.add(5); + + } + + @Test + public void testAddObject() { + list.add(5); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testAddInt() { + list.add(5); + list.add(2, 9); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testRemoveInt() { + Object o = list.remove(0); + System.out.println(o); + System.out.println(list.size()); + } + + + @Test + public void testAddFirst() { + list.addFirst(5); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testAddLast() { + list.addLast(5); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testRemoveFirst() { + list.addFirst(8); + Object o = list.removeFirst(); + System.out.println(o); + } + + @Test + public void testRemoveLast() { + Object o = list.removeLast(); + System.out.println(o); + } + + + @Test + public void testRemoveDuplicateValues() { + list.removeDuplicateValues(); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testRemoveRange() { + list.removeRange(2,5); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testGetElements() { + LinkedList list1 = new LinkedList(); + list1.add(2); + list1.add(5); + int[] a = list.getElements(list1); + for (int i = 0; i < a.length; i++) { + System.out.println(a[i]); + } + } + + @Test + public void testRemove() { + list.remove(2,2); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testRemoveFirstHalf() { + list.removeFirstHalf(); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testSubtract() { + LinkedList list1 = new LinkedList(); + list1.add(8); + list1.add(5); + list.subtract(list1); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } + + @Test + public void testReverse() { + list.reverse(); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } +} diff --git a/group18/1159828430/20160305/src/com/coding/download/DownloadThread.java b/group18/1159828430/20160305/src/com/coding/download/DownloadThread.java new file mode 100644 index 0000000000..f7148fe73d --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/DownloadThread.java @@ -0,0 +1,36 @@ +package com.coding.download; + +import com.coding.download.api.Connection; +import com.coding.download.impl.FileUtil; + +public class DownloadThread extends Thread{ + + Connection conn; + FileUtil file; + int startPos; + int endPos; + + public DownloadThread(Connection conn, FileUtil file, int startPos, int endPos) { + + this.conn = conn; + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + try { + + byte[] data = conn.read(startPos, endPos); + int length = endPos - startPos; + file.writeFile(data, startPos, length); + + } catch (Exception e) { + //System.out.println("线程执行出错"+e.getLocalizedMessage()); + e.printStackTrace(); + } finally { + conn.close(); + file.close(); + } + } + +} diff --git a/group18/1159828430/20160305/src/com/coding/download/FileDownloader.java b/group18/1159828430/20160305/src/com/coding/download/FileDownloader.java new file mode 100644 index 0000000000..20c3ae60d0 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/FileDownloader.java @@ -0,0 +1,87 @@ +package com.coding.download; + +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; +import com.coding.download.api.ConnectionManager; +import com.coding.download.api.DownloadListener; +import com.coding.download.impl.FileUtil; + + +public class FileDownloader { + + private String url; + + private DownloadListener listener; + + private ConnectionManager cm; + + private FileUtil file; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + long length = conn.getContentLength(); + + file.setSize((long)length); + + long sublen = length/3; + + for(int i=0; i<3; i++){ + conn = cm.open(this.url); + int starPos = (int) (sublen * i); + int endPos = (int) (sublen *(i + 1) -1); + new DownloadThread(conn, file, starPos, endPos).run(); + + } + listener.notifyFinished(); + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + conn.close(); + file.close(); + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + public void setFile(FileUtil file) { + this.file = file; + } + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group18/1159828430/20160305/src/com/coding/download/FileDownloaderTest.java b/group18/1159828430/20160305/src/com/coding/download/FileDownloaderTest.java new file mode 100644 index 0000000000..8c4a56cad7 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/FileDownloaderTest.java @@ -0,0 +1,61 @@ +package com.coding.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coding.download.api.ConnectionManager; +import com.coding.download.api.DownloadListener; +import com.coding.download.impl.ConnectionManagerImpl; +import com.coding.download.impl.FileUtil; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://gss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/5ab5c9ea15ce36d33274da5e3cf33a87e950b168.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + FileUtil file = new FileUtil("F:\\test.jpg"); + downloader.setFile(file); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + } + +} diff --git a/group18/1159828430/20160305/src/com/coding/download/api/Connection.java b/group18/1159828430/20160305/src/com/coding/download/api/Connection.java new file mode 100644 index 0000000000..160c318382 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/api/Connection.java @@ -0,0 +1,21 @@ +package com.coding.download.api; + +public interface Connection{ + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws ConnectionException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group18/1159828430/20160305/src/com/coding/download/api/ConnectionException.java b/group18/1159828430/20160305/src/com/coding/download/api/ConnectionException.java new file mode 100644 index 0000000000..70d419d5c7 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/api/ConnectionException.java @@ -0,0 +1,11 @@ +package com.coding.download.api; + +public class ConnectionException extends Exception { + public ConnectionException() { + System.out.println("未知错误"); + } + + public ConnectionException(String msg) { + System.out.println(msg); + } +} diff --git a/group18/1159828430/20160305/src/com/coding/download/api/ConnectionManager.java b/group18/1159828430/20160305/src/com/coding/download/api/ConnectionManager.java new file mode 100644 index 0000000000..1d1a83caf2 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coding.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group18/1159828430/20160305/src/com/coding/download/api/DownloadListener.java b/group18/1159828430/20160305/src/com/coding/download/api/DownloadListener.java new file mode 100644 index 0000000000..c41045b0e8 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coding.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionImpl.java b/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..f40d99011c --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionImpl.java @@ -0,0 +1,79 @@ +package com.coding.download.impl; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; + +public class ConnectionImpl implements Connection { + + private HttpURLConnection conn; + + private BufferedInputStream inputStream; + + public ConnectionImpl (String urlLocation) throws ConnectionException { + + URL url = null; + + try{ + if (urlLocation != null && !"".equals(urlLocation)) { + url = new URL(urlLocation); + } + + conn = (HttpURLConnection) url.openConnection(); + conn.setReadTimeout(10000); + conn.setRequestMethod("GET"); + conn.setAllowUserInteraction(true); + } catch(Exception e) { + throw new ConnectionException("创建Connection对象失败"); + } + + + } + + @Override + public byte[] read(int startPos, int endPos) throws ConnectionException { + int readBytes = 0; + int length = endPos - startPos + 1; + byte[] buf = new byte[length]; + conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + try { + inputStream = new BufferedInputStream(conn.getInputStream()); + while (readBytes < length) { + int read = inputStream.read(buf, readBytes, length - readBytes); + if (read == -1) { + break; + } + readBytes += read; + } + + } catch (Exception e) { + + throw new ConnectionException("读取失败"+e.getMessage()); + } + + return buf; + } + + @Override + public int getContentLength() { + + return conn.getContentLength(); + } + + + @Override + public void close() { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + System.out.println("关闭失败"); + } + } + } + +} diff --git a/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionManagerImpl.java b/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..4f9e732b9b --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coding.download.impl; + +import com.coding.download.api.Connection; +import com.coding.download.api.ConnectionException; +import com.coding.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String urlLocation) throws ConnectionException { + Connection conn = new ConnectionImpl(urlLocation); + return conn; + } + +} diff --git a/group18/1159828430/20160305/src/com/coding/download/impl/FileUtil.java b/group18/1159828430/20160305/src/com/coding/download/impl/FileUtil.java new file mode 100644 index 0000000000..67b6fac7c9 --- /dev/null +++ b/group18/1159828430/20160305/src/com/coding/download/impl/FileUtil.java @@ -0,0 +1,59 @@ +package com.coding.download.impl; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * @author Scholar + * @Time:2017年3月11日 上午12:32:15 + * @version 1.0 + */ +public class FileUtil { + + private File file; + + private RandomAccessFile itemFile; + + public FileUtil(String fileLocation) { + if (fileLocation != null && !"".equals(fileLocation)) { + file = new File(fileLocation); + } + + try { + itemFile = new RandomAccessFile(file, "rw"); + + } catch (IOException e) { + System.out.println("创建随机读写实例失败"); + } + + } + + public void writeFile(byte[] data, int startPos, int length) { + try { + itemFile = new RandomAccessFile(file, "rw"); + itemFile.seek(startPos); + itemFile.write(data, 0, length); + } catch (IOException e) { + System.out.println("文件写入失败"); + } + } + + public void close() { + if (itemFile != null) { + try { + itemFile.close(); + } catch (IOException e) { + System.out.println("文件流关闭失败"); + } + } + } + + public void setSize(long size) { + try { + itemFile.setLength(size); + } catch (IOException e) { + System.out.println("创建指定文件失败"); + } + } +} diff --git a/group18/1159828430/20170226/.classpath b/group18/1159828430/20170226/.classpath new file mode 100644 index 0000000000..2dcf9f7eab --- /dev/null +++ b/group18/1159828430/20170226/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/group18/1159828430/20170226/.gitignore b/group18/1159828430/20170226/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group18/1159828430/20170226/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group18/1159828430/20170226/.project b/group18/1159828430/20170226/.project new file mode 100644 index 0000000000..30be1e8fb2 --- /dev/null +++ b/group18/1159828430/20170226/.project @@ -0,0 +1,17 @@ + + + 20170226 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group18/1159828430/20170226/lib/dom4j-1.6.1.jar b/group18/1159828430/20170226/lib/dom4j-1.6.1.jar new file mode 100644 index 0000000000..c8c4dbb92d Binary files /dev/null and b/group18/1159828430/20170226/lib/dom4j-1.6.1.jar differ diff --git a/group18/1159828430/20170226/lib/jaxen-1.1-beta-6.jar b/group18/1159828430/20170226/lib/jaxen-1.1-beta-6.jar new file mode 100644 index 0000000000..6cef35dac4 Binary files /dev/null and b/group18/1159828430/20170226/lib/jaxen-1.1-beta-6.jar differ diff --git a/group18/1159828430/20170226/src/com/coding/array/ArrayUtil.java b/group18/1159828430/20170226/src/com/coding/array/ArrayUtil.java new file mode 100644 index 0000000000..c634a3a0b6 --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/array/ArrayUtil.java @@ -0,0 +1,216 @@ +package com.coding.array; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * @author Scholar + * @Time:2017年2月27日 下午8:46:07 + * @version 1.0 + */ +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + * @return + */ + public static int[] reverseArray(int[] origin){ + for (int i = 0; i < origin.length/2; i++) { + int temp = origin[i]; + origin[i] = origin[origin.length-i-1]; + origin[origin.length-i-1] = temp; + } + return origin; + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public static int[] removeZero(int[] oldArray){ + //正常方式 + /*List list = new ArrayList(); + for (int i : oldArray) + if (i != 0) + list.add(i); + + int[] newArray = new int[list.size()]; + for (int i = 0; i < newArray.length; i++) { + newArray[i] = list.get(i); + }*/ + //jdk1.8 + IntStream intStream = Arrays.stream(oldArray); + int[] newArray = intStream.filter(i -> i != 0).toArray(); + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public static int[] merge(int[] array1, int[] array2){ + int lena = array1.length; + int lenb = array2.length; + int[] newArray = new int[lena + lenb]; + int i = 0, j = 0, k = 0;// 分别代表数组a ,b , c 的索引 + + while (i < array1.length && j < array2.length) + if (array1[i] <= array2[j]) { + if (k == 0 || newArray[k - 1] != array1[i]) // 去重复 + newArray[k++] = array1[i]; + i++; + } else { + if (k == 0 || newArray[k - 1] != array2[j]) // 去重复 + newArray[k++] = array2[j]; + j++; + } + + while (i < array1.length) { + if (k == 0 || newArray[k - 1] != array1[i]) // 去重复 + newArray[k++] = array1[i]; + i++; + } + while (j < array2.length) { + if (k == 0 || newArray[k - 1] != array2[j]) // 去重复 + newArray[k++] = array2[j]; + j++; + } + newArray = removeZero(newArray); + return newArray; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public static int[] grow(int [] oldArray, int size){ + oldArray = Arrays.copyOf(oldArray, oldArray.length + size); + return oldArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static int[] fibonacci(int max){ + List list = new ArrayList(); + if (max == 1) { + int[] newArr = null; + return newArr; + } else { + for (int i = 0; i <= max; i++) { + int value = fibonacciSequence(i); + if (value < max) { + list.add(value); + } else { + break; + } + } + } + int[] newArray = list.stream().mapToInt(i -> i).toArray(); + return newArray; + } + + private static int fibonacciSequence(int n){ + if(n < 2){ + return 1; + }else{ + return fibonacciSequence(n-1) + fibonacciSequence(n-2); + } + } + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + @SuppressWarnings("unused") + public static int[] getPrimes(int max){ + List list = new ArrayList(); + for (int i = 2; i < max; i++) { + list.add(i); + for (int j = 2; j <= Math.sqrt(i); j++) { + if (i % j == 0){ + Integer temp = i; + list.remove(temp); + break; + } + } + } + + int[] newArray = list.stream().mapToInt(i -> i).toArray(); + return newArray; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public static int[] getPerfectNumbers(int max){ + List list = new ArrayList(); + int[] newArray = null; + if (!(max < 6)) {//第一个完数为6 + for (int i = 6; i < max; i++) { + int sum = 0; + for (int j = 1; j <= i/2; j++) { + if (i % j == 0) { + sum += j; + } + } + if (sum == i) { + list.add(i); + } + System.out.println(i); + } + newArray = list.stream().mapToInt(i -> i).toArray(); + } + return newArray; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public static String join(int[] array, String seperator){ + StringBuilder str = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + str.append(array[i]); + if(i != array.length - 1){ + str.append(seperator); + } + } + return str.toString(); + } + +} + diff --git a/group18/1159828430/20170226/src/com/coding/array/ArrayUtilTest.java b/group18/1159828430/20170226/src/com/coding/array/ArrayUtilTest.java new file mode 100644 index 0000000000..575c02540c --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/array/ArrayUtilTest.java @@ -0,0 +1,81 @@ +package com.coding.array; + +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.Test; + +/** + * @author Scholar + * @Time:2017年3月4日 上午9:12:27 + * @version 1.0 + */ +public class ArrayUtilTest { + + @Test + public void testReverseArray(){ + int[] oldArr = {7, 9 , 30, 3}; + int[] newArr = ArrayUtil.reverseArray(oldArr); + int[] resultArr = {3, 30 , 9, 7}; + assertArrayEquals(resultArr, newArr); + + } + + @Test + public void testRemoveZero() { + int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; + int[] newArr = ArrayUtil.removeZero(oldArr); + int[] resultArr = {1,3,4,5,6,6,5,4,7,6,7,5}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testMerge() { + int[] a1 = {3,5,7,8}; + int[] a2 = {4, 5, 6,7}; + int[] newArr = ArrayUtil.merge(a1, a2); + int[] resultArr = {3,4,5,6,7,8}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testGrow() { + int[] oldArr = {2,3,6}; + int[] newArr = ArrayUtil.grow(oldArr, 3); + int[] resultArr = {2,3,6,0,0,0}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testFibonacci() { + int[] newArr = ArrayUtil.fibonacci(15); + int[] resultArr = {1, 1, 2, 3, 5, 8, 13}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testGetPrimes() { + int[] newArr = ArrayUtil.getPrimes(23); + int[] resultArr = {2,3,5,7,11,13,17,19}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testGetPerfectNumbers() { + int[] newArr = ArrayUtil.getPerfectNumbers(500); + int[] resultArr = {6, 28, 496}; + assertArrayEquals(resultArr, newArr); + } + + @Test + public void testJoin() { + int[] oldArr = {3,8,9}; + String resultStr = ArrayUtil.join(oldArr, "-"); + String str = "3-8-9"; + assertEquals(str, resultStr); + } + +} diff --git a/group18/1159828430/20170226/src/com/coding/litestruts/LoginAction.java b/group18/1159828430/20170226/src/com/coding/litestruts/LoginAction.java new file mode 100644 index 0000000000..308a0c17fd --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/litestruts/LoginAction.java @@ -0,0 +1,38 @@ +package com.coding.litestruts; +/** + * @author Scholar + * @Time:2017年2月27日 下午8:50:23 + * @version 1.0 + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} \ No newline at end of file diff --git a/group18/1159828430/20170226/src/com/coding/litestruts/Struts.java b/group18/1159828430/20170226/src/com/coding/litestruts/Struts.java new file mode 100644 index 0000000000..6cab5bb017 --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/litestruts/Struts.java @@ -0,0 +1,84 @@ +package com.coding.litestruts; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +/** + * @author Scholar + * @Time:2017年2月27日 下午8:49:47 + * @version 1.0 + */ +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + try {//多行代码需要try catch时,如何合理使用try cath和throw Exception? + Element actionElement = getElement("action", actionName); + //实例化action并设置参数 + String actionAdress = actionElement.attribute("class").getText(); + Class actionClass = Class.forName(actionAdress); + Object actionObj = actionClass.newInstance(); + for (Entry entry : parameters.entrySet()) { + Method setMethod = actionClass.getMethod("set"+initStr(entry.getKey()), String.class); + setMethod.invoke(actionObj, entry.getValue()); + } + + //执行execute + Method executeMethod = actionClass.getMethod("execute"); + //Type returnType = m.getGenericReturnType();//获取返回值类型 + String returnValue = (String)executeMethod.invoke(actionObj);//这里如何根据返回类型来动态接收方法的返回值? + //selenium + //获取返回值放到view + Map params = new HashMap(); + Field[] fields = actionClass.getDeclaredFields(); + for (Field field : fields) { + Method m = actionClass.getMethod("get"+initStr(field.getName())); + params.put(field.getName(), (String) m.invoke(actionObj)); + } + Class viewClass = View.class; + Object viewObj = viewClass.newInstance(); + Field paramField = viewClass.getDeclaredField("parameters"); + paramField.setAccessible(true); + paramField.set(viewObj, params); + + //将对应result的值赋值给view并返回view对象 + Element resultElement = getElement("result", returnValue); + String jsp = resultElement.getStringValue(); + Method setJsp = viewClass.getMethod("setJsp", String.class); + return (View)setJsp.invoke(viewObj, jsp); + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + //DOM4J结合XPATH解析XML,取得相应的节点 + private static Element getElement(String node, String name){ + Document document; + Element element = null; + try { + File file = new File("src/com/coding/litestruts/struts.xml"); + SAXReader reader = new SAXReader(); + document = reader.read(file); + element = (Element) document.selectSingleNode("//"+ node + "[@name='" + name + "']"); + } catch (Exception e) { + System.out.println("读取XML失败"); + } + return element; + } + + // 将单词的首字母大写 + public static String initStr(String old){ + String str = old.substring(0,1).toUpperCase() + old.substring(1) ; + return str ; + } +} \ No newline at end of file diff --git a/group18/1159828430/20170226/src/com/coding/litestruts/StrutsTest.java b/group18/1159828430/20170226/src/com/coding/litestruts/StrutsTest.java new file mode 100644 index 0000000000..4bf614bbbc --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coding.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Scholar + * @Time:2017年2月27日 下午8:51:23 + * @version 1.0 + */ +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} \ No newline at end of file diff --git a/group18/1159828430/20170226/src/com/coding/litestruts/View.java b/group18/1159828430/20170226/src/com/coding/litestruts/View.java new file mode 100644 index 0000000000..3c7175350a --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/litestruts/View.java @@ -0,0 +1,27 @@ +package com.coding.litestruts; + +import java.util.Map; +/** + * @author Scholar + * @Time:2017年2月27日 下午8:49:10 + * @version 1.0 + */ +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} \ No newline at end of file diff --git a/group18/1159828430/20170226/src/com/coding/litestruts/struts.xml b/group18/1159828430/20170226/src/com/coding/litestruts/struts.xml new file mode 100644 index 0000000000..60f2bc6c41 --- /dev/null +++ b/group18/1159828430/20170226/src/com/coding/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group20/1040154728/1040154728Learning/src/ArrayList.java b/group20/1040154728/1040154728Learning/week1/src/ArrayList.java similarity index 95% rename from group20/1040154728/1040154728Learning/src/ArrayList.java rename to group20/1040154728/1040154728Learning/week1/src/ArrayList.java index 77fed2b0f4..1b2b6c56cc 100644 --- a/group20/1040154728/1040154728Learning/src/ArrayList.java +++ b/group20/1040154728/1040154728Learning/week1/src/ArrayList.java @@ -1,46 +1,46 @@ -public class ArrayList implements List { - //private fields - private int size = 0; - private Object[] elementData = new Object[100]; - //check if list is empty - public boolean isEmpty() { - return size == 0; - } - - public void add(Object o){ - elementData[size++] = o; - } - public void add(int index, T o){ - /* Not familiar with array copy, copied from GitMori */ - System.arraycopy(elementData, index, elementData, - index + 1, size-index); - elementData[index] = o; - size++; - } - - public T get(int index){ - return (T) elementData[index]; - } - - public T remove(int index){ - T t = this.get(index); - int position = size - index - 1; //why ? - if (position > 0){ - System.arraycopy(elementData, index+1, elementData, - index, position); - } - elementData[--size] = null; - return t; - } - - public int size(){ - return size; - } - - //?? - public Iterator iterator(){ - return null; - } - - -} +public class ArrayList implements List { + //private fields + private int size = 0; + private Object[] elementData = new Object[100]; + //check if list is empty + public boolean isEmpty() { + return size == 0; + } + + public void add(Object o){ + elementData[size++] = o; + } + public void add(int index, T o){ + /* Not familiar with array copy, copied from GitMori */ + System.arraycopy(elementData, index, elementData, + index + 1, size-index); + elementData[index] = o; + size++; + } + + public T get(int index){ + return (T) elementData[index]; + } + + public T remove(int index){ + T t = this.get(index); + int position = size - index - 1; //why ? + if (position > 0){ + System.arraycopy(elementData, index+1, elementData, + index, position); + } + elementData[--size] = null; + return t; + } + + public int size(){ + return size; + } + + //?? + public Iterator iterator(){ + return null; + } + + +} diff --git a/group20/1040154728/1040154728Learning/src/BinaryTreeNode.java b/group20/1040154728/1040154728Learning/week1/src/BinaryTreeNode.java similarity index 94% rename from group20/1040154728/1040154728Learning/src/BinaryTreeNode.java rename to group20/1040154728/1040154728Learning/week1/src/BinaryTreeNode.java index 425894819d..e0d2141b51 100644 --- a/group20/1040154728/1040154728Learning/src/BinaryTreeNode.java +++ b/group20/1040154728/1040154728Learning/week1/src/BinaryTreeNode.java @@ -1,28 +1,28 @@ -public class BinaryTreeNode { - private T data; - private BinaryTreeNode left; - private BinaryTreeNode right; - private int size; - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - public BinaryTreeNode getLeft() { - return left; - } - public void setLeft(BinaryTreeNode left) { - this.left = left; - } - public BinaryTreeNode getRight() { - return right; - } - public void setRight(BinaryTreeNode right) { - this.right = right; - } - - - -} +public class BinaryTreeNode { + private T data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private int size; + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + + +} diff --git a/group20/1040154728/1040154728Learning/src/Iterator.java b/group20/1040154728/1040154728Learning/week1/src/Iterator.java similarity index 94% rename from group20/1040154728/1040154728Learning/src/Iterator.java rename to group20/1040154728/1040154728Learning/week1/src/Iterator.java index 0e1a09433b..9c6eb7e6fb 100644 --- a/group20/1040154728/1040154728Learning/src/Iterator.java +++ b/group20/1040154728/1040154728Learning/week1/src/Iterator.java @@ -1,5 +1,5 @@ -public interface Iterator { - public boolean hasNext(); - public T next(); - -} +public interface Iterator { + public boolean hasNext(); + public T next(); + +} diff --git a/group20/1040154728/1040154728Learning/src/LinkedList.java b/group20/1040154728/1040154728Learning/week1/src/LinkedList.java similarity index 94% rename from group20/1040154728/1040154728Learning/src/LinkedList.java rename to group20/1040154728/1040154728Learning/week1/src/LinkedList.java index 18f6fddf37..3d811f7f83 100644 --- a/group20/1040154728/1040154728Learning/src/LinkedList.java +++ b/group20/1040154728/1040154728Learning/week1/src/LinkedList.java @@ -1,110 +1,110 @@ -public class LinkedList implements List { - - private Node head; - private Node tail; - private int size; - - public void add(T o){ - Node node = new Node(o); - if(head == null) - { - head = node; - } - else - { - tail.next = node; - } - tail = node; - tail.next = null; - size++; - - } - public void add(int index , T o){ - Node node = new Node(o); - Node temp = head; - Node tempTemp = null; - for(int i = 0; i <= index; i++) - { - temp = temp.next; - } - tempTemp = temp.next; - temp.next = node; - node.next = tempTemp; - size++; - } - public T get(int index){ - Node temp = head; - for(int i = 0; i <= index; i++) - { - temp = temp.next; - } - return (T)temp.data; - } - public T remove(int index){ - if(index == 0){ - T o = (T) removeFirst(); - return o; - } - Node temp = head; - Node tempTemp = null; - for(int i = 0; i <= index; i++) - { - temp = temp.next; - } - T o = (T) temp.next.data; - tempTemp = temp.next.next; - temp.next = null; - temp.next = tempTemp; - size--; - return o; - } - - public int size(){ - return size; - } - - @Override - public boolean isEmpty() { - return false; - } - - public void addFirst(T o){ - Node node = new Node(o); - node.next = head; - head = node; - size++; - } - public void addLast(T o){ - this.add(o); - } - public T removeFirst(){ - T o = (T) head.data; - head = head.next; - size--; - return o; - } - public Object removeLast(){ - Node temp = head; - for(int i = 0; i <= size; i++) - { - temp = temp.next; - } - temp.next = null; - T o = (T) tail.data; - tail = temp; - size--; - return o; - } - public Iterator iterator(){ - return null; - } - - - private class Node{ - T data; - Node next; - - public Node(T o) { - } - } -} +public class LinkedList implements List { + + private Node head; + private Node tail; + private int size; + + public void add(T o){ + Node node = new Node(o); + if(head == null) + { + head = node; + } + else + { + tail.next = node; + } + tail = node; + tail.next = null; + size++; + + } + public void add(int index , T o){ + Node node = new Node(o); + Node temp = head; + Node tempTemp = null; + for(int i = 0; i <= index; i++) + { + temp = temp.next; + } + tempTemp = temp.next; + temp.next = node; + node.next = tempTemp; + size++; + } + public T get(int index){ + Node temp = head; + for(int i = 0; i <= index; i++) + { + temp = temp.next; + } + return (T)temp.data; + } + public T remove(int index){ + if(index == 0){ + T o = (T) removeFirst(); + return o; + } + Node temp = head; + Node tempTemp = null; + for(int i = 0; i <= index; i++) + { + temp = temp.next; + } + T o = (T) temp.next.data; + tempTemp = temp.next.next; + temp.next = null; + temp.next = tempTemp; + size--; + return o; + } + + public int size(){ + return size; + } + + @Override + public boolean isEmpty() { + return false; + } + + public void addFirst(T o){ + Node node = new Node(o); + node.next = head; + head = node; + size++; + } + public void addLast(T o){ + this.add(o); + } + public T removeFirst(){ + T o = (T) head.data; + head = head.next; + size--; + return o; + } + public Object removeLast(){ + Node temp = head; + for(int i = 0; i <= size; i++) + { + temp = temp.next; + } + temp.next = null; + T o = (T) tail.data; + tail = temp; + size--; + return o; + } + public Iterator iterator(){ + return null; + } + + + private class Node{ + T data; + Node next; + + public Node(T o) { + } + } +} diff --git a/group20/1040154728/1040154728Learning/src/List.java b/group20/1040154728/1040154728Learning/week1/src/List.java similarity index 95% rename from group20/1040154728/1040154728Learning/src/List.java rename to group20/1040154728/1040154728Learning/week1/src/List.java index eb27d39f6b..addaec468d 100644 --- a/group20/1040154728/1040154728Learning/src/List.java +++ b/group20/1040154728/1040154728Learning/week1/src/List.java @@ -1,8 +1,8 @@ -public interface List { - public void add(T object); - public void add(int index, T object); - public T get(int index); - public T remove(int index); - public int size(); - boolean isEmpty(); -} +public interface List { + public void add(T object); + public void add(int index, T object); + public T get(int index); + public T remove(int index); + public int size(); + boolean isEmpty(); +} diff --git a/group20/1040154728/1040154728Learning/src/Queue.java b/group20/1040154728/1040154728Learning/week1/src/Queue.java similarity index 93% rename from group20/1040154728/1040154728Learning/src/Queue.java rename to group20/1040154728/1040154728Learning/week1/src/Queue.java index b7e03881fe..2da64b2b3c 100644 --- a/group20/1040154728/1040154728Learning/src/Queue.java +++ b/group20/1040154728/1040154728Learning/week1/src/Queue.java @@ -1,22 +1,22 @@ -public class Queue { - - private LinkedList element = new LinkedList(); - - - - public void enQueue(T o){ - element.addLast(o); - } - - public T deQueue(){ - return element.removeFirst(); - } - - public boolean isEmpty(){ - return element.isEmpty(); - } - - public int size(){ - return element.size(); - } -} +public class Queue { + + private LinkedList element = new LinkedList(); + + + + public void enQueue(T o){ + element.addLast(o); + } + + public T deQueue(){ + return element.removeFirst(); + } + + public boolean isEmpty(){ + return element.isEmpty(); + } + + public int size(){ + return element.size(); + } +} diff --git a/group20/1040154728/1040154728Learning/src/Stack.java b/group20/1040154728/1040154728Learning/week1/src/Stack.java similarity index 94% rename from group20/1040154728/1040154728Learning/src/Stack.java rename to group20/1040154728/1040154728Learning/week1/src/Stack.java index 959b081239..9f7b2c7bfa 100644 --- a/group20/1040154728/1040154728Learning/src/Stack.java +++ b/group20/1040154728/1040154728Learning/week1/src/Stack.java @@ -1,21 +1,21 @@ -public class Stack { - private ArrayList elementData = new ArrayList(); - - public void push(Object o){ - elementData.add(o); - } - - public Object pop(){ - return elementData.remove(elementData.size() -1); - } - - public Object peek(){ - return elementData.get(elementData.size()-1); - } - public boolean isEmpty(){ - return elementData.isEmpty(); - } - public int size(){ - return elementData.size(); - } -} +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + return elementData.remove(elementData.size() -1); + } + + public Object peek(){ + return elementData.get(elementData.size()-1); + } + public boolean isEmpty(){ + return elementData.isEmpty(); + } + public int size(){ + return elementData.size(); + } +} diff --git a/group20/1040154728/1040154728Learning/src/honoka.md b/group20/1040154728/1040154728Learning/week1/src/honoka.md similarity index 100% rename from group20/1040154728/1040154728Learning/src/honoka.md rename to group20/1040154728/1040154728Learning/week1/src/honoka.md diff --git a/group20/1040154728/1040154728Learning/week2/ArrayUtil/ArrayUtil.java b/group20/1040154728/1040154728Learning/week2/ArrayUtil/ArrayUtil.java new file mode 100644 index 0000000000..0f09e8a380 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/ArrayUtil/ArrayUtil.java @@ -0,0 +1,230 @@ +import java.util.Arrays; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + if(origin == null || origin.length == 0) { + return; + } + for(int i=0, j = origin.length-1; i < j; i++,j++) { + int t = origin[i]; + origin[i] = origin[j]; + origin[j] = t; + } + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + if(oldArray == null) { + return null; + } + + int counter = 0; // to count how many non-zero numbers + int b[] = new int[oldArray.length]; + //count non-zero numbers + for(int i=0; i < oldArray.length; i++) { + if(oldArray[i] != 0) + { + b[counter++] = oldArray[i]; + } + } + + int newArray[] = new int[counter]; + + return Arrays.copyOf(b,counter); + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + if(array1 == null && array2 == null) { + return null; + } + int [] newArray = new int[array1.length + array2.length]; + + int i = 0; + int j = 0; + int counter = 0; + while(i array2[j]) + { + newArray[counter++] = array2[j++]; + } + else if(array1[i] == array2[j]) + { + newArray[counter++] = array2[j]; + i++; + j++; + } + } + while(i==array1.length && j= max) { + break; + } else { + counter++; + } + } + return Arrays.copyOf(a, counter); + + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max < 3) + return new int[0]; + int[] array = new int[max]; + int counter = 0; + for(int n = 2; n < max; n++) { + if (isPrime(n)) { + array[counter++] = n; + } + } + return Arrays.copyOf(array, counter); + } + + private boolean isPrime(int n) { + int i = 2; + while (i < n) { + if (n % i == 0) { + break; + } + + if (n % i != 0) { + i++; + } + } + return i == n; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + + if(max <= 0) return new int[0]; + + int[] array = new int[max]; + int counter = 0; + for(int n = 2; n < max; n++) + { + int sum = 0; + for(int i = 1; i < n; i++) + { + if(n % i == 0) + { + sum += i; + } + } + if(sum == n) + { + array[counter++] = n; + } + } + return Arrays.copyOf(array,counter); + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @return + */ + public String join(int[] array, String seperator) { + if (array == null) return null; + if(array.length == 0) return ""; + + StringBuilder buffer = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + buffer.append(array[i]); + if (i < array.length - 1) { + buffer.append(seperator); + } + } + return buffer.toString(); + } +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/Configuration.java b/group20/1040154728/1040154728Learning/week2/struts/Configuration.java new file mode 100644 index 0000000000..2db8abf0b5 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/Configuration.java @@ -0,0 +1,113 @@ +package week2.struts; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.input.SAXBuilder; + +public class Configuration { + + Map actions = new HashMap<>(); + + public Configuration(String fileName) { + + String packageName = this.getClass().getPackage().getName(); + + packageName = packageName.replace('.', '/'); + + InputStream is = this.getClass().getResourceAsStream("/" + packageName + "/" + fileName); + + parseXML(is); + + try { + is.close(); + } catch (IOException e) { + throw new ConfigurationException(e); + } + } + + public String getClassName(String action) { + ActionConfig ac = this.actions.get(action); + if(ac == null){ + return null; + } + return ac.getClassName(); + } + + public String getResultView(String actionName, String resultName) { + ActionConfig ac = this.actions.get(actionName); + if(ac == null){ + return null; + } + return ac.getViewName(resultName); + } + + private void parseXML(InputStream is){ + + SAXBuilder builder = new SAXBuilder(); + + try { + + Document doc = builder.build(is); + + Element root = doc.getRootElement(); + + for(Element actionElement : root.getChildren("action")){ + + String actionName = actionElement.getAttributeValue("name"); + String clzName = actionElement.getAttributeValue("class"); + + ActionConfig ac = new ActionConfig(actionName, clzName); + + for(Element resultElement : actionElement.getChildren("result")){ + + String resultName = resultElement.getAttributeValue("name"); + String viewName = resultElement.getText().trim(); + + ac.addViewResult(resultName, viewName); + + } + + this.actions.put(actionName, ac); + } + + + } catch (JDOMException e) { + throw new ConfigurationException(e); + + } catch (IOException e) { + throw new ConfigurationException(e); + + } + + + } + + private static class ActionConfig{ + + String name; + String clzName; + Map viewResult = new HashMap<>(); + + + public ActionConfig(String actionName, String clzName) { + this.name = actionName; + this.clzName = clzName; + } + public String getClassName(){ + return clzName; + } + public void addViewResult(String name, String viewName){ + viewResult.put(name, viewName); + } + public String getViewName(String resultName){ + return viewResult.get(resultName); + } + } + +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/ConfigurationException.java b/group20/1040154728/1040154728Learning/week2/struts/ConfigurationException.java new file mode 100644 index 0000000000..af1fa0aa4d --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/ConfigurationException.java @@ -0,0 +1,20 @@ +package week2.struts; + +import org.jdom2.JDOMException; + +import java.io.IOException; + +/** + * Created by Bugu on 3/17/2017. + */ +public class ConfigurationException extends RuntimeException { + public ConfigurationException(String msg) { + super(msg); + } + public ConfigurationException(JDOMException e) { + super(e); + } + public ConfigurationException(IOException e) { + super(e); + } +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/ConfigurationTest.java b/group20/1040154728/1040154728Learning/week2/struts/ConfigurationTest.java new file mode 100644 index 0000000000..7632a2b0a3 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/ConfigurationTest.java @@ -0,0 +1,45 @@ +package week2.struts; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class ConfigurationTest { + + Configuration cfg = new Configuration("struts.xml"); + + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + @Test + public void testGetClassName() { + String clzName = cfg.getClassName("login"); + Assert.assertEquals("week2.LoginAction",clzName); + clzName = cfg.getClassName("logout"); + Assert.assertEquals("week2.LogoutAction",clzName); + } + + @Test + public void testGetResultView() { + String jsp = cfg.getResultView("login","success"); + Assert.assertEquals("/jsp/homepage.jsp",jsp); + + jsp = cfg.getResultView("login","fail"); + Assert.assertEquals("/jsp/showLogin.jsp",jsp); + + jsp = cfg.getResultView("logout","success"); + Assert.assertEquals("/jsp/welcome.jsp",jsp); + + jsp = cfg.getResultView("logout","error"); + Assert.assertEquals("/jsp/error.jsp",jsp); + } +} \ No newline at end of file diff --git a/group20/1040154728/1040154728Learning/week2/struts/LoginAction.java b/group20/1040154728/1040154728Learning/week2/struts/LoginAction.java new file mode 100644 index 0000000000..b7bf1adc62 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/LoginAction.java @@ -0,0 +1,39 @@ +package week2.struts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtil.java b/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtil.java new file mode 100644 index 0000000000..2c4481b6de --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtil.java @@ -0,0 +1,79 @@ +package week2.struts; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReflectionUtil { + + public static List getSetterMethods(Class clz) { + return getMethods(clz, "set"); + } + + public static void setParameters(Object o, Map params) { + List methods = getSetterMethods(o.getClass()); + for(String name : params.keySet() ){ + String methodName = "set" + name; + for(Method m: methods){ + if(m.getName().equalsIgnoreCase(methodName)){ + try { + m.invoke(o, params.get(name)); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } + } + + public static List getGetterMethods(Class clz) { + return getMethods(clz, "get"); + } + + + public static Map getParameterMap(Object o) { + + Map params = new HashMap<>(); + + List methods = getGetterMethods(o.getClass()); + + for(Method m : methods){ + + String methodName = m.getName(); + String name = methodName.replaceFirst("get", "").toLowerCase(); + try { + Object value = m.invoke(o); + params.put(name, value); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + + return params; + } + + + + + + + + + private static List getMethods(Class clz, String startWithName) { + List methods = new ArrayList<>(); + for(Method m : clz.getDeclaredMethods()) { + if(m.getName().startsWith(startWithName)) { + methods.add(m); + } + } + return methods; + } + + + + + +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtilTest.java b/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtilTest.java new file mode 100644 index 0000000000..e92fd8413a --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/ReflectionUtilTest.java @@ -0,0 +1,111 @@ +package week2.struts; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ReflectionUtilTest { + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetSetterMethod() throws Exception { + String name = "week2.LoginAction"; + Class clz = Class.forName(name); + List methods = ReflectionUtil.getSetterMethods(clz); + + Assert.assertEquals(2, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("setName"); + expectedNames.add("setPassword"); + + Set actualNames = new HashSet<>(); + for(Method m : methods){ + actualNames.add(m.getName()); + } + Assert.assertTrue(actualNames.containsAll(expectedNames)); + } + + @Test + public void testSetParameters() throws Exception{ + + String name = "week2.LoginAction"; + Class clz = Class.forName(name); + Object o = clz.newInstance(); + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + ReflectionUtil.setParameters(o,params); + Field f = clz.getDeclaredField("name"); + f.setAccessible(true); + Assert.assertEquals("test", f.get(o)); + + f = clz.getDeclaredField("password"); + f.setAccessible(true); + Assert.assertEquals("1234", f.get(o)); + } + + @Test + public void testGetGetterMethod() throws Exception{ + String name = "week2.LoginAction"; + Class clz = Class.forName(name); + List methods = ReflectionUtil.getGetterMethods(clz); + + Assert.assertEquals(3, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("getMessage"); + expectedNames.add("getName"); + expectedNames.add("getPassword"); + + Set actualNames = new HashSet<>(); + for(Method m : methods){ + actualNames.add(m.getName()); + } + + Assert.assertTrue(actualNames.containsAll(expectedNames)); + } + + @Test + public void testGetParameters() throws Exception{ + String name = "week2.LoginAction"; + Class clz = Class.forName(name); + LoginAction action = (LoginAction)clz.newInstance(); + action.setName("test"); + action.setPassword("123456"); + + Map params = ReflectionUtil.getParameterMap(action); + + Assert.assertEquals(3, params.size()); + Assert.assertEquals(null, params.get("message") ); + Assert.assertEquals("test", params.get("name") ); + Assert.assertEquals("123456", params.get("password") ); + } + + + + + + + +} \ No newline at end of file diff --git a/group20/1040154728/1040154728Learning/week2/struts/Struts.java b/group20/1040154728/1040154728Learning/week2/struts/Struts.java new file mode 100644 index 0000000000..79c3915dbe --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/Struts.java @@ -0,0 +1,73 @@ +package week2.struts; + +import java.lang.reflect.Method; +import java.util.Map; + + + +public class Struts { + + + private final static Configuration cfg = new Configuration("struts.xml"); + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + + + String clzName = cfg.getClassName(actionName); + + if (clzName == null) { + return null; + } + + try { + Class clz = Class.forName(clzName); + + Object action = clz.newInstance(); + + ReflectionUtil.setParameters(action,parameters); + + Method m = clz.getDeclaredMethod("execute"); + + String resultName = (String)m.invoke(action); + + String jsp = cfg.getResultView(actionName, resultName); + + Map params = ReflectionUtil.getParameterMap(action); + + View view = new View(); + view.setJsp(jsp); + view.setParameters(params); + + return view; + + } + //Encapsulation for each exception is needed + catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/StrutsTest.java b/group20/1040154728/1040154728Learning/week2/struts/StrutsTest.java new file mode 100644 index 0000000000..c422fb84e8 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/StrutsTest.java @@ -0,0 +1,43 @@ +package week2.struts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/View.java b/group20/1040154728/1040154728Learning/week2/struts/View.java new file mode 100644 index 0000000000..2b8c86c49f --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/View.java @@ -0,0 +1,23 @@ +package week2.struts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group20/1040154728/1040154728Learning/week2/struts/struts.xml b/group20/1040154728/1040154728Learning/week2/struts/struts.xml new file mode 100644 index 0000000000..3947abe084 --- /dev/null +++ b/group20/1040154728/1040154728Learning/week2/struts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/DownloadThread.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..52a5fd20a9 --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/DownloadThread.java @@ -0,0 +1,79 @@ +package org.korben.coderising.download; + +import java.io.IOException; +import java.io.RandomAccessFile; +import org.korben.coderising.download.api.Connection; +import org.korben.coderising.download.api.ConnectionException; +import org.korben.coderising.download.api.ConnectionManager; +import org.korben.coderising.download.api.DownloadListener; + +public class DownloadThread extends Thread { + + private int endPos; + private int startPos; + private String url; + private String destFilePath; + private ConnectionManager connManager; + private DownloadListener downloadListener; + + public DownloadThread(ConnectionManager connManager, String url, int startPos, int endPos, String destFilePath, + DownloadListener downloadListener) { + + this.url = url; + this.endPos = endPos; + this.startPos = startPos; + this.connManager = connManager; + this.destFilePath = destFilePath; + this.downloadListener = downloadListener; + } + + @Override + public void run() { + Connection conn = null; + RandomAccessFile randomAccessFile = null; + try { + doLog("BIN"); + conn = connManager.open(url, startPos, endPos); + byte[] read = conn.read(startPos, endPos); + String _filePath = destFilePath; + if (_filePath == null || _filePath.length() == 0) { + _filePath = conn.getFileName(); + } + randomAccessFile = new RandomAccessFile(_filePath, "rw"); + randomAccessFile.seek(startPos); + randomAccessFile.write(read); + doLog("END"); + } catch (IOException e) { + doLog("EXP"); + e.printStackTrace(); + } catch (ConnectionException e) { + doLog("EXP"); + e.printStackTrace(); + } finally { + if (randomAccessFile != null) { + try { + randomAccessFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (conn != null) { + conn.close(); + } + if (downloadListener != null) { + downloadListener.notifyFinished(); + } + } + } + + private void doLog(String action) { + System.out.println( + "*********** " + action + + " [" + + startPos + + "-" + + endPos + + "]" + + " ***********"); + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloader.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..43fde0b69e --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloader.java @@ -0,0 +1,81 @@ +package org.korben.coderising.download; + +import java.util.concurrent.atomic.AtomicInteger; +import org.korben.coderising.download.api.ConnectionException; +import org.korben.coderising.download.api.ConnectionManager; +import org.korben.coderising.download.api.DownloadListener; + +public class FileDownloader { + + private String url; + + private DownloadListener listener; + + private ConnectionManager cm; + + private AtomicInteger atomicInteger; + + public FileDownloader(String _url) { + this.url = _url; + atomicInteger = new AtomicInteger(); + } + + /** + * 在这里实现你的代码, 注意: 需要用多线程实现下载 + * 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + * (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + * (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + * 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + * 具体的实现思路: + * 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + * 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + * 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + * 3. 把byte数组写入到文件中 + * 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + * + * 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + */ + public void execute() { + try { + + int threadCount = 5; + int length = this.cm.getContentLength(this.url); + for (int i = 0; i < threadCount; i++) { + + int threadLoadLength = length / threadCount; + int startPos = threadLoadLength * i; + int endPos; + if (i != threadCount - 1) { + endPos = threadLoadLength * (i + 1) - 1; + } else { + endPos = length - 1; + } + atomicInteger.getAndIncrement(); + new DownloadThread(cm, this.url, startPos, endPos, null, new DownloadListener() { + @Override + public void notifyFinished() { + if (atomicInteger.decrementAndGet() == 0) { + if (FileDownloader.this.listener != null) { + FileDownloader.this.listener.notifyFinished(); + } + } + } + }).start(); + } + } catch (ConnectionException e) { + e.printStackTrace(); + } + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public DownloadListener getListener() { + return this.listener; + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloaderTest.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..53b6b6e45e --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/FileDownloaderTest.java @@ -0,0 +1,54 @@ +package org.korben.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.korben.coderising.download.api.ConnectionManager; +import org.korben.coderising.download.api.DownloadListener; +import org.korben.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + + boolean downloadFinished = false; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489721424&di=1fda6467501ab1d5e5bff43e801d14ee&imgtype=jpg&er=1&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201507%2F30%2F20150730163204_A24MX.thumb.700_0.jpeg"; + //String url = "http://apache.fayea.com/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"; + + FileDownloader downloader = new FileDownloader(url); + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + }); + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/Connection.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/Connection.java new file mode 100644 index 0000000000..6f58852d56 --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/Connection.java @@ -0,0 +1,33 @@ +package org.korben.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return 读取的字节数组 + */ + byte[] read(int startPos, int endPos) throws IOException; + + /** + * 得到数据内容的长度 + * + * @return 数据内容长度 + */ + int getContentLength(); + + /** + * 关闭连接 + */ + void close(); + + /** + * 获取下载文件的文件名 + * + * @return 文件名 + */ + String getFileName(); +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionException.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..d74b432783 --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionException.java @@ -0,0 +1,11 @@ +package org.korben.coderising.download.api; + +public class ConnectionException extends Exception { + public ConnectionException(Exception e) { + super(e); + } + + public ConnectionException(String msg) { + super(msg); + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionManager.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..5e0d4afe3f --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/ConnectionManager.java @@ -0,0 +1,21 @@ +package org.korben.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * + * @param url 连接地址 + * @param startPos 读取文件的起始位置 + * @param endPos 读取文件的结束位置 + * @return 连接 + */ + Connection open(String url, int startPos, int endPos) throws ConnectionException; + + /** + * 获取文件长度 + * + * @param url 连接地址 + * @return 文件长度 + */ + int getContentLength(String url) throws ConnectionException; +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/DownloadListener.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..e2685665b7 --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package org.korben.coderising.download.api; + +public interface DownloadListener { + void notifyFinished(); +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionImpl.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..cce16fafbe --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,93 @@ +package org.korben.coderising.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import org.korben.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection { + + private static final int BUFFER_SIZE = 4096; + private HttpURLConnection httpConn; + private String fileUrl; + private InputStream inputStream; + + public ConnectionImpl(HttpURLConnection httpConn, String fileUrl) { + this.httpConn = httpConn; + this.fileUrl = fileUrl; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + if (endPos < startPos) { + throw new IllegalArgumentException("argument endPos[" + endPos + "] less than startPos[" + startPos + "]"); + } + int bytesNeed2Read = endPos - startPos + 1; + if (bytesNeed2Read > getContentLength()) { + throw new IllegalArgumentException( + "endPos[" + endPos + "] is bigger than content length[" + getContentLength() + "]"); + } + + inputStream = httpConn.getInputStream(); + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[Math.min(bytesNeed2Read, BUFFER_SIZE)]; + int read; + + long startTime = System.currentTimeMillis(); + final long progressInterval = 2000; + while ((read = inputStream.read(buffer)) != -1) { + byteArrayOutputStream.write(buffer, 0, read); + + if (System.currentTimeMillis() - startTime > progressInterval) { + startTime = System.currentTimeMillis(); + System.out.println(String.format(Thread.currentThread().getName() + + " [%.2f%%]", byteArrayOutputStream.size() * 100.0 / bytesNeed2Read) + ); + } + } + System.out.println(String.format(Thread.currentThread().getName() + " [%.2f%%]", 100.0)); + System.out.println("bytes read: " + byteArrayOutputStream.size()); + + return byteArrayOutputStream.toByteArray(); + } + + @Override + public int getContentLength() { + if (httpConn != null) { + return httpConn.getContentLength(); + } + return 0; + } + + @Override + public void close() { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (httpConn != null) { + httpConn.disconnect(); + } + } + + @Override + public String getFileName() { + String disposition = httpConn.getHeaderField("Content-Disposition"); + if (disposition != null) { + // extracts file name from header field + int index = disposition.indexOf("filename="); + if (index > 0) { + return disposition.substring(index + 10, + disposition.length() - 1); + } + } + // extracts file name from URL + return fileUrl.substring(fileUrl.lastIndexOf("/") + 1, + fileUrl.length()); + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionManagerImpl.java b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..16d8df8f7c --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,60 @@ +package org.korben.coderising.download.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import org.korben.coderising.download.api.Connection; +import org.korben.coderising.download.api.ConnectionException; +import org.korben.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String fileURL, int startPos, int endPos) throws ConnectionException { + try { + System.out.println("try to open file url: " + fileURL); + + URL url = new URL(fileURL); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + + // 设定读取range + httpConn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + System.out.println("Range: bytes=" + startPos + "-" + endPos); + + int responseCode = httpConn.getResponseCode(); + + System.out.println("server replied HTTP code: " + responseCode); + if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) { + System.out.println("return new ConnectionImpl"); + return new ConnectionImpl(httpConn, fileURL); + } else { + throw new ConnectionException("server replied HTTP code: " + responseCode); + } + } catch (IOException e) { + throw new ConnectionException(e); + } + } + + @Override + public int getContentLength(String fileURL) throws ConnectionException { + try { + System.out.println("try to open file url: " + fileURL); + + URL url = new URL(fileURL); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + int responseCode = httpConn.getResponseCode(); + + System.out.println("server replied HTTP code: " + responseCode); + if (responseCode == HttpURLConnection.HTTP_OK) { + System.out.println("return contentLength: " + httpConn.getContentLength()); + int contentLength = httpConn.getContentLength(); + httpConn.disconnect(); + return contentLength; + } else { + throw new ConnectionException("server replied HTTP code: " + responseCode); + } + } catch (IOException e) { + throw new ConnectionException(e); + } + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KArrayList.java b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KArrayList.java index 0f443462ed..5df5408e67 100644 --- a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KArrayList.java +++ b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KArrayList.java @@ -74,7 +74,7 @@ public void clear() { @Override @SuppressWarnings("unchecked") public T get(int index) { - if (index < -1 || index >= size) { + if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } @@ -83,7 +83,7 @@ public T get(int index) { @Override public T set(int index, T element) { - if (index < -1 || index >= size) { + if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } @@ -94,7 +94,7 @@ public T set(int index, T element) { @Override public void add(int index, T element) { - if (index < -1 || index > size) { + if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } @@ -109,7 +109,7 @@ public void add(int index, T element) { @Override @SuppressWarnings("unchecked") public T remove(int index) { - if (index < -1 || index >= size) { + if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } @@ -132,7 +132,7 @@ public int indexOf(T o) { @Override public KIterator iterator() { - return new ArrayListIterator(this); + return new ArrayListIterator(); } private void ensureCapacity(int minCapacity) { @@ -147,21 +147,19 @@ private void ensureCapacity(int minCapacity) { private class ArrayListIterator implements KIterator { private int position; - private KArrayList list; - ArrayListIterator(KArrayList list) { - this.list = list; + ArrayListIterator() { } @Override public boolean hasNext() { - return position < list.size(); + return position < size(); } @Override public T next() { if (hasNext()) { - return list.get(position++); + return get(position++); } return null; } diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedList.java b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedList.java index 2ca4452981..5f0975d3fb 100644 --- a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedList.java +++ b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedList.java @@ -1,5 +1,7 @@ package org.korben.coding.basic.list; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; /** @@ -43,19 +45,17 @@ public boolean contains(Object o) { @Override public Object[] toArray() { - return new Object[0]; + throw new IllegalStateException("方法未实现"); } @Override public boolean add(T o) { if (this.last == null) { this.last = new Node<>(o); - this.last.pre = this.head; this.head.next = this.last; } else { Node oldLast = this.last; this.last = new Node<>(o); - this.last.pre = oldLast; oldLast.next = this.last; } this.size++; @@ -65,14 +65,12 @@ public boolean add(T o) { @Override public boolean remove(T o) { Node node = this.head; + Node preNode; while (node.next != null) { + preNode = node; node = node.next; if (Objects.equals(node.data, o)) { - node.pre.next = node.next; - if (node.next != null) { - node.next.pre = node.pre; - } - this.size--; + removeNode(preNode, node); return true; } } @@ -101,30 +99,37 @@ public T set(int index, T element) { @Override public void add(int index, T element) { + ensureIndex(index); + Node node = this.head; + Node preNode = node; for (int i = 0; i <= index; i++) { + preNode = node; node = node.next; } - Node pre = node.pre; + Node newNode = new Node<>(element); - pre.next = newNode; - newNode.pre = pre; newNode.next = node; - node.pre = newNode; + preNode.next = newNode; this.size++; } @Override public T remove(int index) { - Node node = getNode(index); - Node pre = node.pre; - Node next = node.next; - pre.next = next; - if (next != null) { - next.pre = pre; + ensureIndex(index); + + Node node = this.head; + Node preNode = this.head; + for (int i = 0; i <= index; i++) { + preNode = node; + node = node.next; } + preNode.next = node.next; + if (node == last) { + last = preNode; + } this.size--; return node.data; } @@ -145,13 +150,11 @@ public int indexOf(T o) { @Override public KIterator iterator() { - throw new IllegalStateException("方法未实现"); + return new Iterator(); } private Node getNode(int index) { - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException(); - } + ensureIndex(index); Node node = this.head; for (int i = 0; i <= index; i++) { @@ -160,13 +163,333 @@ private Node getNode(int index) { return node; } + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + // 链表为空, 不用逆置, 返回 + if (this.head.next == null) { + return; + } + + // 只有一个元素, 不用逆置, 返回 + if (this.head.next.next == null) { + return; + } + + this.last = this.head.next; + + Node preNode = this.head.next; + Node node = preNode.next; + Node nextNode = node.next; + while (nextNode != null) { + node.next = preNode; + + preNode = node; + node = nextNode; + nextNode = nextNode.next; + } + + node.next = preNode; + this.head.next = node; + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf() { + if (isEmpty()) { + return; + } + + int halfIndex = (this.size) / 2; + + if (halfIndex >= 0) { + this.head.next = getNode(halfIndex); + } + + this.size -= halfIndex; + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + */ + public void remove(int i, int length) { + ensureIndex(i); + ensureIndex(i + length - 1); + + int newSize = this.size - length; + + // 得到被删除起始元素的前一个节点 + Node preNode; + if (i == 0) { + preNode = this.head; + } else { + preNode = getNode(i - 1); + } + + // 得到最后一个被删除的元素 + Node node = preNode.next; + while (--length > 0) { + node = node.next; + } + + // 删除元素 + preNode.next = node.next; + + // 如果被删除的元素包含最后的节点, 改变最后节点 + if (i + length == this.size - 1) { + this.last = preNode; + } + + this.size = newSize; + } + + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + */ + public int[] getElements(KLinkedList list) { + if (list == null || list.size == 0) { + return new int[0]; + } + + List resultList = new ArrayList<>(); + + Node node = this.head; + + KIterator listIterator = list.iterator(); + int elementIndex = (int) listIterator.next(); + for (int i = 0; i < this.size; i++) { + node = node.next; + if (elementIndex == i) { + resultList.add((Integer) node.data); + if (listIterator.hasNext()) { + elementIndex = (int) listIterator.next(); + } else { + break; + } + } + } + + // list 2 array + int[] result = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + result[i] = resultList.get(i); + } + return result; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + */ + public void subtract(KLinkedList list) { + if (list == null || list.size() == 0) { + return; + } + + KIterator listIterator = list.iterator(); + + Node node = this.head; + Node pre; + while (listIterator.hasNext()) { + + int listData = listIterator.next(); + while (node.next != null) { + pre = node; + node = node.next; + + if (listData == (int) node.data) { + removeNode(pre, node); + } else if (listData < (int) node.data) { + break; + } + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + if (this.size() <= 1) { + return; + } + + Node node = this.head; + Node pre; + + while (node.next.next != null) { + pre = node; + node = node.next; + + if (node.data == node.next.data) { + removeNode(pre, node); + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + */ + public void removeRange(int min, int max) { + Node preMinNode = null; + Node maxNode = null; + Node node = this.head; + + // get min and max + int minIndex = -1; + int maxIndex = -1; + while (node.next != null) { + maxIndex++; + if (preMinNode == null) { + minIndex++; + if ((int) node.next.data == min) { + preMinNode = node; + } + } else if ((int) node.next.data == max) { + maxNode = node.next; + } else if (maxNode != null && (int) node.next.data > (int) maxNode.data) { + break; + } + + node = node.next; + } + + // do remove + if (preMinNode != null) { + if (maxNode != null) { + preMinNode.next = maxNode.next; + this.size -= maxIndex - minIndex + 1; + if (preMinNode.next == null) { + this.last = preMinNode; + } + } else { + preMinNode.next = null; + this.size = minIndex; + this.last = preMinNode; + } + } + } + + /** + * 123456789876543 + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + */ + public KLinkedList intersection(KLinkedList list) { + if (list == null || list.size() == 0) { + return copyList(this); + } + if (this.isEmpty()) { + return copyList(list); + } + + KLinkedList resultList = new KLinkedList(); + + KIterator listIterator = list.iterator(); + KIterator iterator = this.iterator(); + Integer listValue = (Integer) listIterator.next(); + Integer value = (Integer) iterator.next(); + for (int i = 0; i < list.size() + this.size() - 1; i++) { + + if (listValue == null) { + if (value != null) { + resultList.add(value); + continue; + } else { + break; + } + } + + if (value == null) { + if (listValue != null) { + resultList.add(listValue); + listValue = (Integer) listIterator.next(); + continue; + } else { + break; + } + } + + if (listValue <= value) { + resultList.add(listValue); + listValue = (Integer) listIterator.next(); + value = (Integer) iterator.next(); + } else { + resultList.add(value); + value = (Integer) iterator.next(); + } + } + + return resultList; + } + + private KLinkedList copyList(KLinkedList linkedList) { + if (linkedList == null) { + return null; + } + + KLinkedList result = new KLinkedList(); + KIterator iterator = linkedList.iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return result; + } + + private void ensureIndex(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + } + + private void removeNode(Node pre, Node node) { + pre.next = node.next; + this.size--; + if (this.last == node) { + this.last = pre; + } + } + private static class Node { T data; - Node pre; Node next; Node(T data) { this.data = data; } } + + private class Iterator implements KIterator { + private Node node; + + Iterator() { + this.node = head; + } + + @Override + public boolean hasNext() { + return node.next != null; + } + + @Override + public T next() { + if (hasNext()) { + node = node.next; + return node.data; + } + return null; + } + } } diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedListTest.java b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedListTest.java new file mode 100644 index 0000000000..f086efdbdc --- /dev/null +++ b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KLinkedListTest.java @@ -0,0 +1,157 @@ +package org.korben.coding.basic.list; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * 链表测试--第三次算法作业 + * + * Created by Korben on 07/03/2017. + */ +public class KLinkedListTest { + + private KLinkedList linkedList; + + @Before + public void init() { + linkedList = new KLinkedList<>(); + for (int i = 0; i < 5; i++) { + linkedList.add(i); + } + } + + @Test + public void reverse() throws Exception { + // 测试多个 + linkedList.reverse(); + Assert.assertEquals(linkedList.size(), 5); + for (int i = 0; i < 5; i++) { + Assert.assertEquals(linkedList.get(i).intValue(), 4 - i); + } + + // 测试空链表 + linkedList = new KLinkedList<>(); + linkedList.reverse(); + Assert.assertEquals(linkedList.size(), 0); + + // 测试单个 + linkedList.add(0); + linkedList.reverse(); + Assert.assertEquals(linkedList.size(), 1); + Assert.assertEquals(linkedList.get(0).intValue(), 0); + } + + @Test + public void removeFirstHalf() throws Exception { + linkedList.removeFirstHalf(); + Assert.assertEquals(linkedList.size(), 3); + for (int i = 0; i < 3; i++) { + Assert.assertEquals(linkedList.get(i).intValue(), i + 2); + } + + linkedList = new KLinkedList<>(); + linkedList.removeFirstHalf(); + Assert.assertEquals(linkedList.size(), 0); + } + + @Test + public void remove() throws Exception { + // 测试删除开始节点 + { + linkedList.remove(0, 2); + Assert.assertEquals(linkedList.size(), 3); + for (int i = 0; i < 3; i++) { + Assert.assertEquals(linkedList.get(i).intValue(), i + 2); + } + } + + // 测试删除中间节点 + { + init(); + linkedList.remove(1, 2); + Assert.assertEquals(linkedList.size(), 3); + Assert.assertEquals(linkedList.get(0).intValue(), 0); + Assert.assertEquals(linkedList.get(1).intValue(), 3); + Assert.assertEquals(linkedList.get(2).intValue(), 4); + } + + // 测试删除末尾节点 + { + init(); + linkedList.remove(3, 2); + Assert.assertEquals(linkedList.size(), 3); + Assert.assertEquals(linkedList.get(0).intValue(), 0); + Assert.assertEquals(linkedList.get(1).intValue(), 1); + Assert.assertEquals(linkedList.get(2).intValue(), 2); + } + + // 测试删除全部 + { + init(); + linkedList.remove(0, 5); + Assert.assertEquals(linkedList.size(), 0); + } + } + + @Test + public void getElements() throws Exception { + KLinkedList list = new KLinkedList<>(); + list.add(2); + list.add(4); + + int[] elements = linkedList.getElements(list); + Assert.assertEquals(elements.length, 2); + Assert.assertEquals(elements[0], linkedList.get(2).intValue()); + Assert.assertEquals(elements[1], linkedList.get(4).intValue()); + } + + @Test + public void subtract() throws Exception { + KLinkedList list = new KLinkedList<>(); + list.add(2); + list.add(4); + + linkedList.subtract(list); + Assert.assertEquals(linkedList.size(), 3); + Assert.assertEquals(linkedList.get(0).intValue(), 0); + Assert.assertEquals(linkedList.get(1).intValue(), 1); + Assert.assertEquals(linkedList.get(2).intValue(), 3); + } + + @Test + public void removeDuplicateValues() throws Exception { + linkedList = new KLinkedList<>(); + for (int i = 0; i < 10; i++) { + linkedList.add(i / 2); + } + + linkedList.removeDuplicateValues(); + Assert.assertEquals(linkedList.size(), 5); + for (int i = 0; i < 5; i++) { + Assert.assertEquals(linkedList.get(i).intValue(), i); + } + } + + @Test + public void removeRange() throws Exception { + linkedList.removeRange(2, 4); + Assert.assertEquals(linkedList.size(), 2); + Assert.assertEquals(linkedList.get(0).intValue(), 0); + Assert.assertEquals(linkedList.get(1).intValue(), 1); + } + + @Test + public void intersection() throws Exception { + KLinkedList insertList = new KLinkedList(); + for (int i = 3; i < 8; i++) { + insertList.add(i); + } + + KLinkedList intersection = linkedList.intersection(insertList); + Assert.assertEquals(intersection.size(), 8); + for (int i = 0; i < intersection.size(); i++) { + Assert.assertEquals(intersection.get(i), i); + } + } +} \ No newline at end of file diff --git a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KListTest.java b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KListTest.java index 2c6febecc3..d789318174 100644 --- a/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KListTest.java +++ b/group20/1107837739/1107837739Learning/src/org/korben/coding/basic/list/KListTest.java @@ -24,6 +24,9 @@ public void init() { // 测试KLinkedList list = new KLinkedList<>(); + //// 测试KDoubleLinkedList + //list = new KDoubleLinkedList<>(); + initTestSize = 5; for (int i = 0; i < initTestSize; i++) { diff --git a/group20/1107837739/korben.md b/group20/1107837739/korben.md index 91ee50808b..1259561cb0 100644 --- a/group20/1107837739/korben.md +++ b/group20/1107837739/korben.md @@ -5,5 +5,5 @@ | Blog Title | Date| | ---------- | -----------| | [初窥计算机程序的运行](http://korben-chy.github.io/2017/02/26/%E5%88%9D%E7%AA%A5%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A8%8B%E5%BA%8F%E7%9A%84%E8%BF%90%E8%A1%8C/) | 2017/02/26 | -| -[程序在计算机中的运行过程简析](http://korben-chy.github.io/2017/03/06/%E7%A8%8B%E5%BA%8F%E5%9C%A8%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%B8%AD%E7%9A%84%E8%BF%90%E8%A1%8C%E8%BF%87%E7%A8%8B%E7%AE%80%E6%9E%90) | 2017/03/05 | +| [程序在计算机中的运行过程简析](http://korben-chy.github.io/2017/03/06/%E7%A8%8B%E5%BA%8F%E5%9C%A8%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%B8%AD%E7%9A%84%E8%BF%90%E8%A1%8C%E8%BF%87%E7%A8%8B%E7%AE%80%E6%9E%90) | 2017/03/05 | +| [并发编程之-Volatile浅析](http://korben-chy.github.io/2017/03/12/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E4%B9%8B-Volatile%E6%B5%85%E6%9E%90) | 2017/03/12 | diff --git a/group20/404130810/src/com/coderising/download/DownloadThread.java b/group20/404130810/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..02e36f5d10 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,45 @@ +package com.coderising.download; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.CountDownLatch; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + CountDownLatch latch; + + File file = new File("C://download.mp3"); + + public DownloadThread( Connection conn, int startPos, int endPos, CountDownLatch latch){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.latch = latch; + } + public void run(){ + RandomAccessFile raf = null; + try { + byte[] byteRead = conn.read(startPos, endPos); + raf = new RandomAccessFile(file, "rw");; + raf.seek(startPos); + raf.write(byteRead); + + } catch (IOException e) { + e.printStackTrace(); + }finally{ + latch.countDown(); + try { + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } + conn.close(); + } + } +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/FileDownloader.java b/group20/404130810/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..0619cdbc32 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,85 @@ +package com.coderising.download; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; +import com.coderising.download.utils.FileDownloadUtil; + +public class FileDownloader { + + String url = "http://localhost:8080/MyServer/test.exe"; + + DownloadListener listener; + + ConnectionManager cm; + + public FileDownloader(String _url) { + this.url = _url; + cm = new ConnectionManagerImpl(); + } + + public void execute() throws IOException { + // ʵĴ룬 ע⣺ Ҫö߳ʵ + // ӿ, Ҫд⼸ӿڵʵִ + // (1) ConnectionManager , ԴһӣͨConnectionԶȡеһΣstartPos, + // endPosָ + // (2) DownloadListener, Ƕ߳أ Ŀͻ˲֪ʲôʱҪʵֵ + // ̶ִ߳Ժ listenernotifiedFinished ͻ˾յ֪ͨ + // ʵ˼· + // 1. ҪConnectionManageropenӣ + // ȻͨConnection.getContentLengthļij + // 2. 3߳أ עÿ߳ҪȵConnectionManageropen + // Ȼread readжȡļĿʼλúͽλõIJ ֵbyte[] + // 3. byteд뵽ļ + // 4. е̶߳Ժ ҪlistenernotifiedFinished + + // Ĵʾ룬 Ҳ˵ֻһ̣߳ Ҫɶ̵߳ġ + Connection conn = null; + try { + conn = cm.open(url); + int length = conn.getContentLength(); + int[] posArr = FileDownloadUtil.generateDownloadPosArr(length); + CountDownLatch latch = new CountDownLatch(3); + for (int i = 0; i < posArr.length; i++) { + if (i == posArr.length - 1) { + new DownloadThread(cm.open(url), posArr[i], length, latch).start(); + } else { + new DownloadThread(cm.open(url), posArr[i], posArr[i + 1] - 1, latch).start(); + } + } + latch.await(); + System.out.println("Download Finished"); + } catch (ConnectionException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public DownloadListener getListener() { + return this.listener; + } + + public static void main(String[] args) throws IOException { + new FileDownloader("http://localhost:8080/MyServer/Test.mp3").execute(); + } + +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/FileDownloaderTest.java b/group20/404130810/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..784ec00c8a --- /dev/null +++ b/group20/404130810/src/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,60 @@ +package com.coderising.download; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() throws IOException { + + String url = "http://localhost:8080/MyServer/Test.mp3"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/api/Connection.java b/group20/404130810/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..249da5d667 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/api/ConnectionException.java b/group20/404130810/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..8dbfe95dda --- /dev/null +++ b/group20/404130810/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group20/404130810/src/com/coderising/download/api/ConnectionManager.java b/group20/404130810/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..aba5b931e4 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + public Connection open(String url) throws ConnectionException; +} diff --git a/group20/404130810/src/com/coderising/download/api/DownloadListener.java b/group20/404130810/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..4cd0b3eab1 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group20/404130810/src/com/coderising/download/impl/ConnectionImpl.java b/group20/404130810/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..0970d41749 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,64 @@ +package com.coderising.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.net.HttpURLConnection; +import java.net.URL; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection { + + private HttpURLConnection httpConn; + + public ConnectionImpl(String urlStr) { + URL url; + try { + url = new URL(urlStr); + httpConn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + System.out.println("Start Reading"); + System.out.println("StartPos: " + startPos); + System.out.println("EndPos: " + endPos); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + InputStream is = httpConn.getInputStream(); + is.skip(startPos); + + int downloadLengh = endPos - startPos; + + byte[] b = new byte[1024]; + int total = 0; + int len = -1; + while ((len = is.read(b)) != -1) { + baos.write(b, 0, len); + total = total + len; + if (total == downloadLengh) { + break; + } + } + is.close(); + baos.close(); + System.out.println("End Reading"); + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + return httpConn.getContentLength(); + } + + @Override + public void close() { + httpConn.disconnect(); + } + +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group20/404130810/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..9b9a93a9ea --- /dev/null +++ b/group20/404130810/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,13 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + @Override + public Connection open(String urlStr) throws ConnectionException { + Connection conn = new ConnectionImpl(urlStr); + return conn; + } +} \ No newline at end of file diff --git a/group20/404130810/src/com/coderising/download/utils/FileDownloadUtil.java b/group20/404130810/src/com/coderising/download/utils/FileDownloadUtil.java new file mode 100644 index 0000000000..3f8d727d59 --- /dev/null +++ b/group20/404130810/src/com/coderising/download/utils/FileDownloadUtil.java @@ -0,0 +1,20 @@ +package com.coderising.download.utils; + +public class FileDownloadUtil { + + public static int[] generateDownloadPosArr(int length){ + int[] posArr = new int[3]; + int firstPos = length/3; + int secondPos = length/3 * 2; + + posArr[0] = 0; + posArr[1] = firstPos; + posArr[2] = secondPos; + + return posArr; + } + public static void main(String[] args) { + FileDownloadUtil.generateDownloadPosArr(1000); + } + +} diff --git a/group20/592146505/coderising/src/org/wsc/array/ArrayUtil.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtil.java similarity index 99% rename from group20/592146505/coderising/src/org/wsc/array/ArrayUtil.java rename to group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtil.java index 7bba1bb77b..3caef64d35 100644 --- a/group20/592146505/coderising/src/org/wsc/array/ArrayUtil.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtil.java @@ -1,4 +1,4 @@ -package org.wsc.array; +package org.wsc.coderising.array; public class ArrayUtil { /** diff --git a/group20/592146505/coderising/src/org/wsc/array/ArrayUtilTest.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtilTest.java similarity index 98% rename from group20/592146505/coderising/src/org/wsc/array/ArrayUtilTest.java rename to group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtilTest.java index 009dec2938..e459aa175f 100644 --- a/group20/592146505/coderising/src/org/wsc/array/ArrayUtilTest.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/array/ArrayUtilTest.java @@ -1,4 +1,4 @@ -package org.wsc.array; +package org.wsc.coderising.array; import static org.junit.Assert.*; diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/DownloadThread.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..d6b8a4abf0 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/DownloadThread.java @@ -0,0 +1,61 @@ +package org.wsc.coderising.download; + +import java.io.IOException; +import java.io.RandomAccessFile; + +import org.wsc.coderising.download.api.Connection; +import org.wsc.coderising.download.api.ConnectionException; +import org.wsc.coderising.download.api.DownloadListener; + +/** + * 下载线程 + * + * @author Administrator + * @date 2017年3月6日下午7:03:41 + * @version v1.0 + * + */ +public class DownloadThread extends Thread{ + + private RandomAccessFile accessFile; + /** 连接 */ + private Connection conn; + /** 开始处 */ + private int startPos; + /** 结束处 */ + private int endPos; + /** 回调函数 */ + private DownloadListener listener; + + public DownloadThread( Connection conn, int startPos, int endPos,DownloadListener listener){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.listener = listener; + } + public void run(){ + try { + byte[] bt = conn.read(startPos, endPos); + accessFile = new RandomAccessFile("./"+conn.getFileName(), "rw"); + accessFile.seek(startPos); + accessFile.write(bt); + } catch (IOException e) { + e.printStackTrace(); + } catch (ConnectionException e) { + e.printStackTrace(); + }finally { + if(accessFile != null){ + try { + accessFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (conn != null) + conn.close(); + if(listener!=null) + listener.notifyFinished(); + } + + } +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloader.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..f9c3afd9e2 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloader.java @@ -0,0 +1,88 @@ +package org.wsc.coderising.download; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.wsc.coderising.download.api.Connection; +import org.wsc.coderising.download.api.ConnectionException; +import org.wsc.coderising.download.api.ConnectionManager; +import org.wsc.coderising.download.api.DownloadListener; + +/** + * 文件下载器 + * + * @author Administrator + * @date 2017年3月6日下午7:04:44 + * @version v1.0 + * + */ +public class FileDownloader { + private final static int THREAD_NUM = 10; + + private String url; + + private DownloadListener listener; + + private ConnectionManager cm; + + private AtomicInteger atomicInteger = new AtomicInteger(); + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + try { + int length = cm.getContentLength(url); + int perThred_length = length/THREAD_NUM; + int redundant = length%THREAD_NUM; + for (int i = 0; i < THREAD_NUM; i++) { + int startPos = i*perThred_length; + int endPos = (i+1)*perThred_length-1; + if(i == THREAD_NUM -1)//最后一个线程 + endPos+=redundant; + Connection conn = cm.open(this.url); + atomicInteger.getAndIncrement(); + new DownloadThread(conn,startPos,endPos,new DownloadListener() { + @Override + public void notifyFinished() { + if(atomicInteger.decrementAndGet()==0) + listener.notifyFinished(); + } + }).start(); + } + + } catch (ConnectionException e) { + e.printStackTrace(); + } + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloaderTest.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..cca38600df --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/FileDownloaderTest.java @@ -0,0 +1,53 @@ +package org.wsc.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wsc.coderising.download.api.ConnectionManager; +import org.wsc.coderising.download.api.DownloadListener; +import org.wsc.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + // 资源位置 + String url = "http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg"; + // 创建资源下载器实例 + FileDownloader downloader = new FileDownloader(url); + // 创建连接管理实例 + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + // 生成回调函数 + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + // 开始下载 + downloader.execute(); + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + // 休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!请刷新项目根目录"); + } + +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/Connection.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/Connection.java new file mode 100644 index 0000000000..12318aa441 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/Connection.java @@ -0,0 +1,44 @@ +package org.wsc.coderising.download.api; + +import java.io.IOException; + +/** + * 连接接口 + * + * @author Administrator + * @date 2017年3月6日下午7:00:53 + * @version v1.0 + * + */ +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * + * @param startPos + * 开始位置, 从0开始 + * @param endPos + * 结束位置 + * @return + * @throws IOException + * @throws ConnectionException + */ + public byte[] read(int startPos, int endPos) throws IOException, ConnectionException; + + /** + * 得到数据内容的长度 + * + * @return + */ + public int getContentLength(); + + /** + * 获取文件名称 + * @return + */ + public String getFileName(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionException.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..da1ff9c2d5 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionException.java @@ -0,0 +1,37 @@ +package org.wsc.coderising.download.api; + +/** + * + * 连接异常类 + * + * @author Administrator + * @date 2017年3月6日下午6:59:41 + * @version v1.0 + * + */ +public class ConnectionException extends Exception { + + private static final long serialVersionUID = -249834831447340792L; + + public ConnectionException() { + super(); + } + + public ConnectionException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public ConnectionException(String message, Throwable cause) { + super(message, cause); + } + + public ConnectionException(String message) { + super(message); + } + + public ConnectionException(Throwable cause) { + super(cause); + } + +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionManager.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..16ad03ca28 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/ConnectionManager.java @@ -0,0 +1,29 @@ +package org.wsc.coderising.download.api; + +/** + * + * 连接池接口 + * + * @author Administrator + * @date 2017年3月6日下午7:02:30 + * @version v1.0 + * + */ +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * + * @param url + * @return + * @throws ConnectionException + */ + Connection open(String url) throws ConnectionException; + + /** + * 获取长度 + * @param urlStr + * @return + * @throws ConnectionException + */ + int getContentLength(String urlStr) throws ConnectionException; +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/DownloadListener.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..5d785032d0 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/api/DownloadListener.java @@ -0,0 +1,17 @@ +package org.wsc.coderising.download.api; + +/** + * + * 下载监听接口 + * + * @author Administrator + * @date 2017年3月6日下午7:02:58 + * @version v1.0 + * + */ +public interface DownloadListener { + /** + * 通知下载完成回调函数 + */ + public void notifyFinished(); +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionImpl.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..befa4cf0e8 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,115 @@ +package org.wsc.coderising.download.impl; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; + +import org.wsc.coderising.download.api.Connection; +import org.wsc.coderising.download.api.ConnectionException; + +/** + * + * 连接类 + * + * @author Administrator + * @date 2017年3月6日下午7:10:13 + * @version v1.0 + * + */ +public class ConnectionImpl implements Connection { + + /** 默认缓冲大小 */ + private final static int DEFAULT_SIZE = 1024; + + private HttpURLConnection conn; + + private InputStream is; + + private ByteArrayOutputStream bos; + + @SuppressWarnings("static-access") + @Override + public byte[] read(int startPos, int endPos) throws IOException, ConnectionException { + // 设置读取范围 + conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + conn.setFollowRedirects(true);//自动执行重定向 + conn.setConnectTimeout(30000);//等待响应时间 + checkStatus(); + byte[] buf = new byte[Math.min(getContentLength(), DEFAULT_SIZE)]; + is = new BufferedInputStream(conn.getInputStream()); + bos = new ByteArrayOutputStream(); + int lenth;//实际读取长度 + //读取 + while ((lenth = is.read(buf))!= -1) + bos.write(buf, 0, lenth); + return bos.toByteArray(); + } + + @Override + public int getContentLength() { + return conn.getContentLength(); + } + + @Override + public void close() { + if (bos != null) + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if (is != null) + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if(conn != null) + conn.disconnect(); + } + + @Override + public String getFileName() { + String fileName = null; + String field = conn.getHeaderField("Content-Disposition"); + if(field == null ){ + String urlStr = conn.getURL().toString(); + fileName = urlStr.substring(urlStr.lastIndexOf("/")+1); + }else{ + fileName=field.substring(field.indexOf("filename")+10, field.length()-1); + } + System.out.println(fileName); + return fileName; + } + + /** + * 检查连接状态 + * @throws ConnectionException + */ + private void checkStatus() throws ConnectionException { + try { + int responseCode = conn.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_PARTIAL) { + throw new ConnectionException("server response code: " + responseCode); + } + } catch (IOException e) { + throw new ConnectionException(e); + } + } + + public HttpURLConnection getConn() { + return conn; + } + + public void setConn(HttpURLConnection conn) { + this.conn = conn; + } + + public ConnectionImpl(HttpURLConnection conn) { + super(); + this.conn = conn; + } + +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionManagerImpl.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..35be908776 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,70 @@ +package org.wsc.coderising.download.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.wsc.coderising.download.api.Connection; +import org.wsc.coderising.download.api.ConnectionException; +import org.wsc.coderising.download.api.ConnectionManager; + +/** + * 连接池类 + * + * @author Administrator + * @date 2017年3月6日下午7:11:50 + * @version v1.0 + * + */ +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String _url) throws ConnectionException { + HttpURLConnection connection = getConnection(_url); + return new ConnectionImpl(connection); + } + + @Override + public int getContentLength(String _url) throws ConnectionException { + HttpURLConnection connection = getConnection(_url); + int length = 0; + try { + checkStatus(connection); + length = connection.getContentLength(); + } catch (IOException e) { + new ConnectionException(e); + }finally { + connection.disconnect(); + } + return length; + } + + private HttpURLConnection getConnection(String _url) throws ConnectionException{ + URL url = null; + HttpURLConnection connection = null; + try { + url = new URL(_url); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + return connection; + } catch (IOException e) { + new ConnectionException(e); + } + return null; + } + + /** + * 检查连接状态 + * @param connection + * @throws IOException + * @throws ConnectionException + */ + private void checkStatus(HttpURLConnection connection) throws IOException, ConnectionException { + int responseCode = connection.getResponseCode(); + System.out.println("server response code: " + responseCode); + if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_PARTIAL) { + throw new ConnectionException("server response code: " + responseCode); + } + } + +} diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/Action.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Action.java similarity index 87% rename from group20/592146505/coderising/src/org/wsc/litestruts/Action.java rename to group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Action.java index 083519bac6..87d08cf4cd 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/Action.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Action.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts; +package org.wsc.coderising.litestruts; import java.util.Set; diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/LoginAction.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..47abe6d963 --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package org.wsc.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/Struts.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Struts.java similarity index 96% rename from group20/592146505/coderising/src/org/wsc/litestruts/Struts.java rename to group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Struts.java index 30a418979f..33f7804096 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/Struts.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/Struts.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts; +package org.wsc.coderising.litestruts; import java.io.IOException; import java.lang.reflect.Field; @@ -14,7 +14,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.wsc.litestruts.util.DocumentUtil; +import org.wsc.coderising.litestruts.util.DocumentUtil; import org.xml.sax.SAXException; public class Struts { @@ -24,7 +24,7 @@ public class Struts { /* 0. 读取配置文件struts.xml */ DOCUMENT_UTIL = DocumentUtil.newInstance(); try { - document = DOCUMENT_UTIL.getDocument("src/struts.xml"); + document = DOCUMENT_UTIL.getDocument("src/org/wsc/litestruts/struts.xml"); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/StrutsTest.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..bcc10d1e8e --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package org.wsc.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/View.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/View.java new file mode 100644 index 0000000000..c2722f8c2a --- /dev/null +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/View.java @@ -0,0 +1,26 @@ +package org.wsc.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + + public Map getParameters() { + return parameters; + } + + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group20/592146505/coderising/src/struts.xml b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/struts.xml similarity index 100% rename from group20/592146505/coderising/src/struts.xml rename to group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/struts.xml diff --git a/group20/592146505/coderising/src/org/wsc/litestruts/util/DocumentUtil.java b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/util/DocumentUtil.java similarity index 97% rename from group20/592146505/coderising/src/org/wsc/litestruts/util/DocumentUtil.java rename to group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/util/DocumentUtil.java index 9125b244cd..4effa19ab8 100644 --- a/group20/592146505/coderising/src/org/wsc/litestruts/util/DocumentUtil.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coderising/litestruts/util/DocumentUtil.java @@ -1,4 +1,4 @@ -package org.wsc.litestruts.util; +package org.wsc.coderising.litestruts.util; import java.io.File; import java.io.IOException; diff --git a/group20/592146505/data _structure/src/org/wsc/exception/NullElementException.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/NullElementException.java similarity index 90% rename from group20/592146505/data _structure/src/org/wsc/exception/NullElementException.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/NullElementException.java index aa7763ef00..1bafd61d7e 100644 --- a/group20/592146505/data _structure/src/org/wsc/exception/NullElementException.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/NullElementException.java @@ -1,4 +1,4 @@ -package org.wsc.exception; +package org.wsc.coding.basic.exception; /** * diff --git a/group20/592146505/data _structure/src/org/wsc/exception/RepeatingElementException.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/RepeatingElementException.java similarity index 90% rename from group20/592146505/data _structure/src/org/wsc/exception/RepeatingElementException.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/RepeatingElementException.java index a5b66c54a1..63c9172364 100644 --- a/group20/592146505/data _structure/src/org/wsc/exception/RepeatingElementException.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/exception/RepeatingElementException.java @@ -1,4 +1,4 @@ -package org.wsc.exception; +package org.wsc.coding.basic.exception; /** * diff --git a/group20/592146505/data _structure/src/org/wsc/list/ArrayList.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/ArrayList.java similarity index 99% rename from group20/592146505/data _structure/src/org/wsc/list/ArrayList.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/ArrayList.java index 28b8db4132..f12160e752 100644 --- a/group20/592146505/data _structure/src/org/wsc/list/ArrayList.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/ArrayList.java @@ -1,11 +1,9 @@ -package org.wsc.list; +package org.wsc.coding.basic.list; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; -import javafx.stage.StageStyle; - /** * ArrayList类 * diff --git a/group20/592146505/data _structure/src/org/wsc/list/Iterator.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Iterator.java similarity index 86% rename from group20/592146505/data _structure/src/org/wsc/list/Iterator.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Iterator.java index 59590bbf7e..92d1909c35 100644 --- a/group20/592146505/data _structure/src/org/wsc/list/Iterator.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Iterator.java @@ -1,4 +1,4 @@ -package org.wsc.list; +package org.wsc.coding.basic.list; public interface Iterator { /** diff --git a/group20/592146505/data _structure/src/org/wsc/list/LinkedList.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/LinkedList.java similarity index 99% rename from group20/592146505/data _structure/src/org/wsc/list/LinkedList.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/LinkedList.java index b909cfeabc..bcccddfbc1 100644 --- a/group20/592146505/data _structure/src/org/wsc/list/LinkedList.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/LinkedList.java @@ -1,4 +1,4 @@ -package org.wsc.list; +package org.wsc.coding.basic.list; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; diff --git a/group20/592146505/data _structure/src/org/wsc/list/List.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/List.java similarity index 97% rename from group20/592146505/data _structure/src/org/wsc/list/List.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/List.java index 2fd90c6395..bab268a048 100644 --- a/group20/592146505/data _structure/src/org/wsc/list/List.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/List.java @@ -1,4 +1,4 @@ -package org.wsc.list; +package org.wsc.coding.basic.list; /** * List接口 diff --git a/group20/592146505/data _structure/src/org/wsc/list/Queue.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Queue.java similarity index 92% rename from group20/592146505/data _structure/src/org/wsc/list/Queue.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Queue.java index 2087335e58..fb5c83c757 100644 --- a/group20/592146505/data _structure/src/org/wsc/list/Queue.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/list/Queue.java @@ -1,4 +1,4 @@ -package org.wsc.list; +package org.wsc.coding.basic.list; /** * diff --git a/group20/592146505/data _structure/src/org/wsc/stack/Stack.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java similarity index 77% rename from group20/592146505/data _structure/src/org/wsc/stack/Stack.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java index 96b931ca07..09f83c98b6 100644 --- a/group20/592146505/data _structure/src/org/wsc/stack/Stack.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java @@ -1,6 +1,6 @@ -package org.wsc.stack; +package org.wsc.coding.basic.stack; -import org.wsc.list.ArrayList; +import org.wsc.coding.basic.list.ArrayList; public class Stack { private ArrayList elementData = new ArrayList(); diff --git a/group20/592146505/data _structure/src/org/wsc/tree_node/BinaryTreeNode.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/tree_node/BinaryTreeNode.java similarity index 95% rename from group20/592146505/data _structure/src/org/wsc/tree_node/BinaryTreeNode.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/tree_node/BinaryTreeNode.java index b68784541d..eb77f74070 100644 --- a/group20/592146505/data _structure/src/org/wsc/tree_node/BinaryTreeNode.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/tree_node/BinaryTreeNode.java @@ -1,7 +1,7 @@ -package org.wsc.tree_node; +package org.wsc.coding.basic.tree_node; -import org.wsc.exception.NullElementException; -import org.wsc.exception.RepeatingElementException; +import org.wsc.coding.basic.exception.NullElementException; +import org.wsc.coding.basic.exception.RepeatingElementException; /** * BinaryTreeNode 二叉树结构 diff --git "a/group20/755659358/blogs/blog\345\234\260\345\235\200.txt" "b/group20/755659358/blogs/blog\345\234\260\345\235\200.txt" index 82dd8add37..5b1436ee57 100644 --- "a/group20/755659358/blogs/blog\345\234\260\345\235\200.txt" +++ "b/group20/755659358/blogs/blog\345\234\260\345\235\200.txt" @@ -1 +1,2 @@ week02:http://www.jianshu.com/p/22d2cbefdaa1 +week03:http://www.jianshu.com/p/8d1b6373c178 diff --git a/group20/755659358/week03/src/com/coderising/array/ArrayUtil.java b/group20/755659358/week03/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..78845d06d0 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coderising.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/group20/755659358/week03/src/com/coderising/download/DownloadThread.java b/group20/755659358/week03/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..4744709756 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,40 @@ +package com.coderising.download; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread { + + Connection conn; + int startPos; + int endPos; + File file; + + public DownloadThread(Connection conn, int startPos, int endPos, File file) { + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.file = file; + } + + public void run() { + RandomAccessFile raf=null; + try { + raf=new RandomAccessFile(file, "rw"); + raf.seek(startPos); + raf.write(conn.read(startPos, endPos),0,endPos-startPos+1); + } catch (IOException e) { + e.printStackTrace(); + }finally { + try { + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} diff --git a/group20/755659358/week03/src/com/coderising/download/FileDownloader.java b/group20/755659358/week03/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..771506f322 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,89 @@ +package com.coderising.download; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute() { + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, + // endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, + // 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + + try { + + conn = cm.open(this.url); + File file = new File(getFileName(url)); + if (!file.exists()) { + file.createNewFile(); + } + int length = conn.getContentLength(); + RandomAccessFile raf = new RandomAccessFile(file, "rw"); + raf.setLength(length); + raf.close(); + int block=length/3; + new DownloadThread(conn, 0, block, file).start(); + new DownloadThread(conn, block, 2*block, file).start(); + new DownloadThread(conn, 2*block, length-1,file).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + private String getFileName(String filePath) { + return filePath.substring(filePath.lastIndexOf('/') + 1); + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public DownloadListener getListener() { + return this.listener; + } + +} diff --git a/group20/755659358/week03/src/com/coderising/download/FileDownloaderTest.java b/group20/755659358/week03/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..c6be1cea43 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://a.zdmimg.com/201703/11/58c3ff6f422a38093.jpg_c350.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 +// while (!downloadFinished) { +// try { +// System.out.println("还没有下载完成,休眠五秒"); +// //休眠5秒 +// Thread.sleep(5000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// } +// System.out.println("下载完成!"); + + + + } + +} diff --git a/group20/755659358/week03/src/com/coderising/download/TestDown.java b/group20/755659358/week03/src/com/coderising/download/TestDown.java new file mode 100644 index 0000000000..31bd0afd96 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/TestDown.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class TestDown { + + public static void main(String[] args) { + String url = "http://a.zdmimg.com/201703/11/58c3ff6f422a38093.jpg_c350.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.execute(); + + } + +} diff --git a/group20/755659358/week03/src/com/coderising/download/api/Connection.java b/group20/755659358/week03/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..9710e270e1 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group20/755659358/week03/src/com/coderising/download/api/ConnectionException.java b/group20/755659358/week03/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..8dbfe95dda --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group20/755659358/week03/src/com/coderising/download/api/ConnectionManager.java b/group20/755659358/week03/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..fb44ede457 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group20/755659358/week03/src/com/coderising/download/api/DownloadListener.java b/group20/755659358/week03/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..4cd0b3eab1 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group20/755659358/week03/src/com/coderising/download/impl/ConnectionImpl.java b/group20/755659358/week03/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..347c785ea2 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,79 @@ +package com.coderising.download.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import com.coderising.download.api.Connection; +import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; + +public class ConnectionImpl implements Connection { + + private URL httpUrl; + + public ConnectionImpl(String url) { + try { + httpUrl = new URL(url); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + + @Override + public byte[] read(int startPos, int endPos) { + byte[] result = null; + HttpURLConnection conn = null; + ByteOutputStream outByte=null; + try { + conn = (HttpURLConnection) httpUrl.openConnection(); + conn.setRequestMethod("GET"); + conn.setReadTimeout(5000); + conn.addRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + int code = conn.getResponseCode(); + System.out.println("code:" + code); + if (code == 206) { + InputStream in = conn.getInputStream(); + outByte = new ByteOutputStream(); + outByte.write(in); + result=outByte.getBytes(); + } + System.out.println("result:" + result.length); + } catch (IOException e1) { + e1.printStackTrace(); + } finally { + outByte.close(); + conn.disconnect(); + } + + System.out.println(result.length + "resultsize"); + return result; + } + + @Override + public int getContentLength() { + int fileSize = 0; + HttpURLConnection conn = null; + try { + conn = (HttpURLConnection) httpUrl.openConnection(); + conn.setRequestMethod("HEAD"); + conn.setReadTimeout(5000); + if (conn.getResponseCode() == 200) { + fileSize = conn.getContentLength(); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + conn.disconnect(); + } + + return fileSize; + } + + @Override + public void close() { + + } + +} diff --git a/group20/755659358/week03/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group20/755659358/week03/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..f1db9d72a9 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return new ConnectionImpl(url); + } + +} diff --git a/group20/755659358/week03/src/com/coderising/litestruts/LoginAction.java b/group20/755659358/week03/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..1005f35a29 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group20/755659358/week03/src/com/coderising/litestruts/Struts.java b/group20/755659358/week03/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..9761246bed --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,37 @@ +package com.coderising.litestruts; + +import java.lang.reflect.Method; +import java.util.Map; + + + +public class Struts { + + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + + return null; + } + +} diff --git a/group20/755659358/week03/src/com/coderising/litestruts/StrutsTest.java b/group20/755659358/week03/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..a44c1878ac --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group20/755659358/week03/src/com/coderising/litestruts/View.java b/group20/755659358/week03/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..0194c681f6 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group20/755659358/week03/src/com/coderising/litestruts/struts.xml b/group20/755659358/week03/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..4c6eeabbd4 --- /dev/null +++ b/group20/755659358/week03/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group20/755659358/week03/src/com/coding/basic/Iterator.java b/group20/755659358/week03/src/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..dbe8b9afb2 --- /dev/null +++ b/group20/755659358/week03/src/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group20/755659358/week03/src/com/coding/basic/LinkedList.java b/group20/755659358/week03/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..fe6ba359cd --- /dev/null +++ b/group20/755659358/week03/src/com/coding/basic/LinkedList.java @@ -0,0 +1,318 @@ +package com.coding.basic; + +public class LinkedList implements List { + + private Node head; + + private int size = 0; + + public void add(Object o) { + if (size == 0) { + head = new Node(); + head.data = o; + size++; + return; + } + Node last = head; + for (int i = 0; i < size - 1; i++) { + last = last.next; + } + Node added = new Node(); + last.next = added; + added.data = o; + size++; + } + + public void add(int index, Object o) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException(); + } + Node pre = getNode(index - 1); + Node next = getNode(index); + Node addedNode = new Node(); + addedNode.data = o; + pre.next = addedNode; + addedNode.next = next; + size++; + } + + private Node getNode(int index) { + Node node = head; + + for (int i = 0; i < index; i++) { + node = node.next; + } + + return node; + } + + public Object get(int index) { + if (index < 0 || index > size - 1) { + throw new IndexOutOfBoundsException(); + } + if (index == 0 && head == null) { + return null; + } + return getNode(index).data; + + } + + public Object remove(int index) { + if (index < 0 || index > size - 1) { + throw new IndexOutOfBoundsException(); + } + Node pre = getNode(index - 1); + Node next = getNode(index + 1); + pre.next = next; + size--; + return getNode(index); + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + if (head == null) { + head = new Node(); + head.data = o; + size++; + return; + } + Node addNode = new Node(); + addNode.data = o; + addNode.next = head; + head = addNode; + size++; + } + + public void addLast(Object o) { + Node preLast = getNode(size - 1); + Node addNode = new Node(); + addNode.data = o; + preLast.next = addNode; + size++; + } + + public Object removeFirst() { + Node preHead = head; + head = head.next; + size--; + return preHead.data; + } + + public Object removeLast() { + Node preLast = getNode(size - 1); + Node last = getNode(size - 2); + last.next = null; + size--; + return preLast.data; + } + + public LinkedListIterator iterate() { + return new LinkedListIterator(); + } + + public class LinkedListIterator implements Iterator { + + private int position; + + @Override + public boolean hasNext() { + return position < size(); + } + + @Override + public Object next() { + return get(position++); + } + + } + + private static class Node { + + Object data; + Node next; + + } + + /** + * 把该链表逆置 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + Node newHead = getNode(size - 1); + for (int i = size - 1; i > 0; i--) { + getNode(i).next = getNode(i - 1); + } + head = newHead; + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + * + */ + public void removeFirstHalf() { + int half = size / 2; + Node newHead = getNode(half); + for (int i = 0; i < half - 1; i++) { + Node node = getNode(i); + node = null; + } + size -= half; + head = getNode(half); + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + int p = i; + if (i == 0) { + Node newHead = getNode(length); + do { + Node node = getNode(p); + node = null; + p++; + } while (p < length); + head = newHead; + size -= length; + return; + } + + getNode(i - 1).next = getNode(i + length); + size -= length; + for (; p < i + length; p++) { + Node node = getNode(p); + node = null; + } + } + + /** + * 假定当前链表和listB均包含已升序排列的整数 从当前链表中取出那些listB所指定的元素 例如当前链表 = + * 11->101->201->301->401->501->601->701 listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * + * @param list + */ + public int[] getElements(LinkedList list) { + int[] result = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + int index = (int) list.get(i); + result[i] = (int) get(index); + } + return result; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 从当前链表中中删除在listB中出现的元素 + * + * @param list + */ + + public void subtract(LinkedList list) { + + for (int i = 0; i < list.size(); i++) { + int dataB = (int) list.get(i); + for (int j = size - 1; j > 0; j--) { + int data = (int) get(j); + if (data == dataB) { + remove(j); + } + } + } + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + int i = size - 2; + int right = (int) get(i + 1); + int left = (int) get(i); + + do { + if (right == left) { + remove(i); + } else { + right = (int) get(i); + } + i--; + left = (int) get(i); + } while (i > 0); + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + int indexMin=0; + int i = 0; + while (imin) { + indexMin=i; + break; + }else { + i++; + } + } + if (i==size) { + return; + } + + int indexMax=0; + int j=size-1; + while (j>=0) { + int dataMax=(int) get(j); + if (dataMax> implements MyList { + + private Node head;// ָͷʼΪ + // private Node tail;// ָβĽڵ + private int size; + + public MyLinkedList() { + this.head = new Node(null); + this.size = 0; + } + + private static class Node { + Node next = null; + T item = null; + + public Node(T t) { + item = t; + } + + } + + @Override + public boolean add(T t) { + // TODO Auto-generated method stub + return addLast(t); + } + + @Override + public void add(int index, T t) { + // TODO Auto-generated method stub + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException(); + } + Node newNode = new Node(t); + if (index == 0) { + Node oldNode = head.next; + head.next = newNode; + newNode.next = oldNode; + size++; + } + + else { + Node current = getNode(index - 1); + newNode.next = current.next; + current.next = newNode; + size++; + } + + } + + @Override + public int size() { + // TODO Auto-generated method stub + return size; + } + + @Override + public T remove(int index) { + // TODO Auto-generated method stub + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException(); + } else if (index == 0) { + return removeFirst(); + } else if (index == size - 1) { + return removeLast(); + } else { + Node current = getNode(index - 1); + T data = current.next.item; + current.next.item = null; + current.next = current.next.next; + size--; + return data; + } + } + + @Override + public T set(int index, T t) { + // TODO Auto-generated method stub + Node current = getNode(index); + T data = current.item; + current.item = t; + return data; + } + + @Override + public T get(int index) { + // TODO Auto-generated method stub + T data = getNode(index).item; + return data; + } + + public int indexOf(T t) { + Node current = this.head; + int index = 0; + while (current.next != null) { + current = current.next; + if (Objects.equals(current.item, t)) { + return index; + } + index++; + } + return -1; + } + + private Node getNode(int index) { + + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + Node current = this.head; + int m_size = 0; + while (current.next != null && m_size <= index) { + current = current.next; + m_size++; + } + return current; + } + + public boolean addFirst(T t) { + + if (head.next == null) { + Node current = new Node(t); + head.next = current; + current = null; + size++; + return true; + } else { + Node current = new Node(t); + current.next = head.next; + head.next = current; + size++; + return true; + } + } + + public boolean addLast(T t) { + + if (head.next == null) { + Node current = new Node(t); + head.next = current; + current.next = null; + size++; + return true; + } else { + Node current = new Node(t); + Node oldNode = getNode(size - 1); + oldNode.next = current; + current.next = null; + size++; + return true; + } + + } + + public T removeFirst() { + if (head.next == null) { + return null; + } else if (head.next.next == null) { + T data = head.next.item; + head.next.item = null; + head = null; + size--; + return data; + } else { + T data = head.next.item; + Node current = head.next.next; + head.next.item = null; + head.next = current; + size--; + return data; + } + } + + public T removeLast() { + if (head.next == null) { + return null; + } else if (head.next.next == null) { + T data = head.next.item; + head.next.item = null; + size--; + return data; + } else { + Node current = getNode(size - 2); + T data = current.next.item; + current.next.item = null; + current.next = null; + size--; + return data; + } + } + + public boolean isContain(T t){ + + if (head.next == null) { + return false; + } + Node current = head; + while(current.next != null){ + current = current.next; + if (Objects.equals(t, current.item)) { + return true; + } + } + return false; + } + + /** + * Ѹ Ϊ 3->7->10 , úΪ 10->7->3 + */ + public void reverse() { + this.head.next = reverseList(head.next); + } + + private Node reverseList(Node mhead) { + + if (mhead == null || mhead.next == null) { + return mhead; + } + Node reHead = reverseList(mhead.next); + mhead.next.next = mhead; + mhead.next = null; + return reHead; + } + + /** + * ɾһĺ벿 磺list = 2->5->7->8 , ɾԺֵΪ 2->5 list = 2->5->7->8->10 + * ,ɾԺֵΪ2,5,7 + */ + public void removeLastHalf() { + + if (size < 2) { + return; + } + int index = (size - 1) / 2 + 1; + Node current = getNode(index - 1); + Node temp = current; + while (index < size) { + temp = temp.next; + temp.item = null; + index++; + } + size = (size - 1) / 2 + 1; + current.next = null; + } + + /** + * ɾһǰ벿 磺list = 2->5->7->8 , ɾԺֵΪ 7->8 list = 2->5->7->8->10 + * ,ɾԺֵΪ7,8,10 + */ + public void removeFirstHalf() { + + if (size < 2) { + return; + } + int maxIndex = size/ 2; + int index = 0; + Node current = head; + while (index < maxIndex) { + current = current.next; + current.item = null; + index++; + size--; + } + //size = (size - 1) / 2 + 1; + head.next = current.next; + } + + /** + * ӵiԪؿʼ ɾlength Ԫ עi0ʼ + * + * @param i + * @param length + */ + public void remove(int i, int length) { + + if (i < 0 || i >= size || (i + length - 1) > size) { + throw new IndexOutOfBoundsException(); + } + int index = 0; + Node current; + if (i == 0) { + current = head; + } else { + current = getNode(i - 1); + } + Node temp = current; + while (index < length) { + current = current.next; + current.item = null; + index++; + } + if (current.next == null) { + if (i == 0) { + head.next = null; + } else { + temp.next = null; + } + } else { + if (i == 0) { + head.next = current.next; + } else { + temp.next = current.next; + } + } + size = size - length; + + } + + /** + * ٶǰlistе ӵǰȡЩlistָԪ 統ǰ = + * 11->101->201->301->401->501->601->701 listB = 1->3->4->6 + * صĽӦ[101,301,401,601] + * + * @param list + */ + @SuppressWarnings("unchecked") + public int[] getElements(MyLinkedList list) { + int[] elements = new int[list.size]; + int i = 0; + MyIterator iterator = (MyIterator) list.iterator(); + while (iterator.hasNext()) { + int index = iterator.Next(); + if (index < this.size) { + Node current = getNode(index); + elements[i++] = (Integer) current.item; + } else { + elements[i++] = 0;// ûиԪʱֵΪ㣬intͣʱΪnull + } + } + return Arrays.copyOf(elements, i); + } + + /** + * ֪еԪֵУԵ洢ṹ ӵǰɾlistгֵԪ + * + * @param list + */ + + public void subtract(MyLinkedList list) { + + if (list.size == 0) { + return; + } + MyIterator iterator = list.iterator(); + + while (iterator.hasNext()) { + T element = iterator.Next(); + int index = indexOf(element);// ǰ + if (index != -1) { + remove(index); + } + } + } + + /** + * ɾֵͬĶԪأʹòԱԪصֵͬ + */ + public void removeRepeatValues() { + if (head.next == null || head.next.next == null) { + return; + } + // ԼMyArrayList + MyArrayList list = new MyArrayList<>(); + // + Node current = head; + T obj = null; + while (current.next != null) { + current = current.next; + obj = current.item; + if (list.isContain(obj)) { + // int index = indexOf(obj); + remove(indexOf(obj)); // remove(T t) + + } else { + list.add(obj); + } + } + } + + /** + * ֪ǰеԪֵУԵ洢ṹ ɾֵͬĶԪأʹòԱԪصֵͬ + */ + public void removeDuplicateValues() { + + if (head.next == null || head.next.next == null) { + return; + } + Node current = head; + T obj = null; + while (current.next != null) { + current = current.next; + obj = current.item; + if (current.next != null && Objects.equals(obj, current.next.item)) { + // int index = indexOf(obj); + remove(indexOf(obj)); // remove(T t) + } + } + } + + /** + * ֪еԪֵУԵ洢ṹ дһЧ㷨ɾֵminСmaxԪأдԪأ + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + + if (head.next == null) { + return; + } + Node current = head; + Integer integer;// ĿǰֻȽ͵ģӦͣҪʵComparableӿ + while (current.next != null) { + current = current.next; + integer = (Integer) current.item; + if (integer.intValue() > min && integer.intValue() < max) { + remove(indexOf(current.item)); + } + } + } + + /** + * 赱ǰͲlistָԪֵУͬһеԪֵͬ + * ҪCԪΪǰlistԪصĽұCеԪֵ + * + * @param list + */ + public MyLinkedList intersection(MyLinkedList list) { + + if (list.size == 0 || head.next == null) { + return null; + } + MyLinkedList newLinked = new MyLinkedList(); + MyIterator iterator = list.iterator(); + //MyArrayList arrayList = new MyArrayList<>();//û + //ArrayList arrayList = new ArrayList<>(); + TreeSet treeSet = new TreeSet<>(); + + while (iterator.hasNext()) { + T element = iterator.Next(); + if (isContain(element)) { + treeSet.add(element); + } + } + + for(T t : treeSet){ + newLinked.add(t); + } + return newLinked; + + } + /* + @SuppressWarnings("unchecked") + public MyLinkedList union(MyLinkedList list) { + + if (head.next == null) { + + if (list.size == 0) { + return null; + } else { + return list; + } + } else { + if (list.size == 0) { + return this; + } else { + + MyLinkedList newList = new MyLinkedList(); + TreeSet treeSet = new TreeSet<>();// MyArrayListװвͬԪأӵlinkedlist + + Node current = head; + while (current.next != null) { + current = current.next; + treeSet.add(current.item); + } + MyIterator iterator = (MyIterator) list.iterator(); + while (iterator.hasNext()) { + treeSet.add(iterator.Next()); + } + for (T t : treeSet) { + newList.add(t); + } + return newList; + } + } + + } + + */ + public MyIterator iterator() { + + return new LinkedListIterator(); + } + + private class LinkedListIterator implements MyIterator { + + private int current = 0; + T data = null; + + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return (current < size); + } + + @Override + public T Next() { + // TODO Auto-generated method stub + if (hasNext()) { + data = getNode(current).item; + current++; + return data; + } + return null; + } + } + +} diff --git "a/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\225\260\346\215\256\347\273\223\346\236\204\347\273\203\344\271\240/linkedlist/MyLinkedListTest.java" "b/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\225\260\346\215\256\347\273\223\346\236\204\347\273\203\344\271\240/linkedlist/MyLinkedListTest.java" new file mode 100644 index 0000000000..8c3085962a --- /dev/null +++ "b/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\225\260\346\215\256\347\273\223\346\236\204\347\273\203\344\271\240/linkedlist/MyLinkedListTest.java" @@ -0,0 +1,276 @@ +package MyLinkedListTest; + +import static org.junit.Assert.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.ralf.linkedlist.MyLinkedList; + +public class MyLinkedListTest { + + private MyLinkedList list = new MyLinkedList<>(); + @Before + public void setUp() throws Exception { + + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + + } + + @Test + public void reverse() { + + list.reverse(); + Assert.assertEquals(5, list.size()); + for(int i=0; i listA = new MyLinkedList<>(); + listA.add(2); + listA.add(5); + listA.add(7); + listA.add(8); + listA.removeFirstHalf(); + + Assert.assertEquals(2, listA.size()); + Assert.assertEquals(7, listA.get(0).intValue()); + Assert.assertEquals(8, listA.get(1).intValue()); + + } + + @Test + public void removeLastHalf(){ + + list.removeLastHalf(); + Assert.assertEquals(3, list.size()); + + for(int i=0; i listA = new MyLinkedList<>(); + listA.add(2); + listA.add(5); + listA.add(7); + listA.add(8); + listA.removeLastHalf(); + + Assert.assertEquals(2, listA.size()); + Assert.assertEquals(2, listA.get(0).intValue()); + Assert.assertEquals(5, listA.get(1).intValue()); + } + + //remove(int i, int length) + @Test + public void remove(){ + + list.remove(0, 5); + Assert.assertEquals(0, list.size()); + + MyLinkedList listA = new MyLinkedList<>(); + listA.add(2); + listA.add(5); + listA.add(7); + listA.add(8); + listA.add(9); + listA.add(10); + + listA.remove(1, 3); + Assert.assertEquals(3, listA.size()); + Assert.assertEquals(2, listA.get(0).intValue()); + Assert.assertEquals(9, listA.get(1).intValue()); + Assert.assertEquals(10, listA.get(2).intValue()); + } + + + //int[] getElements(MyLinkedList list) + @Test + public void getElements(){ + + MyLinkedList listA = new MyLinkedList<>(); + listA.add(11); + listA.add(101); + listA.add(201); + listA.add(301); + listA.add(401); + listA.add(501); + listA.add(601); + listA.add(701); + + MyLinkedList listB = new MyLinkedList<>(); + listB.add(1); + listB.add(3); + listB.add(4); + listB.add(6); + + int[] aar; + aar = listA.getElements(listB); + Assert.assertEquals(4, aar.length); + + Assert.assertEquals(101, aar[0]); + Assert.assertEquals(301, aar[1]); + Assert.assertEquals(401, aar[2]); + Assert.assertEquals(601, aar[3]); + + } + + + //subtract(MyLinkedList list) + @Test + public void subtract(){ + + MyLinkedList listA = new MyLinkedList<>(); + listA.add(11); + listA.add(101); + listA.add(201); + listA.add(301); + listA.add(401); + listA.add(501); + listA.add(601); + listA.add(701); + + MyLinkedList listB = new MyLinkedList<>(); + listB.add(201); + listB.add(301); + listB.add(501); + listB.add(801); + + listA.subtract(listB); + Assert.assertEquals(5, listA.size()); + + Assert.assertEquals(11, listA.get(0).intValue()); + Assert.assertEquals(101, listA.get(1).intValue()); + Assert.assertEquals(401, listA.get(2).intValue()); + Assert.assertEquals(601, listA.get(3).intValue()); + Assert.assertEquals(701, listA.get(4).intValue()); + } + + @Test + public void removeRepeatValues(){ + //ԼķģɾʱɾǰͬԪ + MyLinkedList listA = new MyLinkedList<>(); + listA.add(11);// + listA.add(101);// + listA.add(101); + listA.add(301);// + listA.add(11); + listA.add(301); + listA.add(201);// + listA.add(701);// + + listA.removeRepeatValues(); + Assert.assertEquals(5, listA.size()); + + Assert.assertEquals(101, listA.get(0).intValue()); + Assert.assertEquals(11, listA.get(1).intValue()); + Assert.assertEquals(301, listA.get(2).intValue()); + Assert.assertEquals(201, listA.get(3).intValue()); + Assert.assertEquals(701, listA.get(4).intValue()); + } + + @Test + public void removeDuplicateValues(){ + + MyLinkedList listA = new MyLinkedList<>(); + + listA.add(11); + listA.add(11); + listA.add(12); + listA.add(13); + listA.add(14); + listA.add(14); + listA.add(15); + listA.add(16); + listA.add(16); + + listA.removeDuplicateValues(); + Assert.assertEquals(6, listA.size()); + + Assert.assertEquals(11, listA.get(0).intValue()); + Assert.assertEquals(12, listA.get(1).intValue()); + Assert.assertEquals(13, listA.get(2).intValue()); + Assert.assertEquals(14, listA.get(3).intValue()); + Assert.assertEquals(15, listA.get(4).intValue()); + Assert.assertEquals(16, listA.get(5).intValue()); + + } + + + //removeRange(int min, int max) + @Test + public void removeRange(){ + + MyLinkedList listA = new MyLinkedList<>(); + + listA.add(11); + listA.add(11); + listA.add(12); + listA.add(13); + listA.add(14); + listA.add(14); + listA.add(15); + listA.add(16); + listA.add(16); + + listA.removeRange(12, 16); + + Assert.assertEquals(5, listA.size()); + Assert.assertEquals(11, listA.get(0).intValue()); + Assert.assertEquals(11, listA.get(1).intValue()); + Assert.assertEquals(12, listA.get(2).intValue()); + Assert.assertEquals(16, listA.get(3).intValue()); + Assert.assertEquals(16, listA.get(4).intValue()); + + } + + @Test + public void intersection(){ + + MyLinkedList list = new MyLinkedList<>(); + MyLinkedList listB = new MyLinkedList<>(); + MyLinkedList listC = new MyLinkedList<>(); + + list.add(11); + list.add(12); + list.add(13); + list.add(14); + list.add(15); + list.add(17); + list.add(18); + + listB.add(10); + listB.add(12); + listB.add(14); + listB.add(15); + listB.add(18); + + + listC = (MyLinkedList) list.intersection(listB); + + Assert.assertEquals(4, listC.size()); + Assert.assertEquals(12, listC.get(0).intValue()); + Assert.assertEquals(14, listC.get(1).intValue()); + Assert.assertEquals(15, listC.get(2).intValue()); + Assert.assertEquals(18, listC.get(3).intValue()); + } + +} diff --git "a/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\226\207\347\253\240\351\223\276\346\216\245.txt" "b/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\226\207\347\253\240\351\223\276\346\216\245.txt" new file mode 100644 index 0000000000..d3f65d64ee --- /dev/null +++ "b/group20/925290009/\347\254\254\344\270\211\346\254\241\344\275\234\344\270\232/\346\226\207\347\253\240\351\223\276\346\216\245.txt" @@ -0,0 +1 @@ +http://blog.csdn.net/u011371324/article/details/61618954 \ No newline at end of file diff --git a/group26/1515345281/src/week1/collection/ArrayList.java b/group26/1515345281/src/week1/collection/ArrayList.java new file mode 100644 index 0000000000..2ba58db6f0 --- /dev/null +++ b/group26/1515345281/src/week1/collection/ArrayList.java @@ -0,0 +1,79 @@ +package week1.collection; + +import java.util.Arrays; + +public class ArrayList implements List { + + private int size=0; + + private Object[] elementData=new Object[100]; + + public void add(Object o){ + + add(size,o); + + } + + public void add(int index, Object o){ + + ListUtils.checkIndexRange(index,size); + + if(size == elementData.length){ + elementData = Arrays.copyOf(elementData, elementData.length+50); + } + + if(index < size){ + for(int i=size-1;i>=index;i--){ + elementData[i+1]=elementData[i]; + } + } + elementData[index] = o; + size++; + } + + public Object get(int index){ + + ListUtils.checkIndexRange(index+1,size); + + return elementData[index]; + } + + public Object remove(int index){ + + ListUtils.checkIndexRange(index+1,size); + + Object object=elementData[index]; + for(int i=index;i 0){ + if(null == currentNode.getLeft()){ + BinaryTreeNode insertNode=new BinaryTreeNode(o); + currentNode.setLeft(insertNode); + return insertNode; + } + currentNode=currentNode.left; + }else{ + if(null ==currentNode.right){ + BinaryTreeNode insertNode=new BinaryTreeNode(o); + currentNode.setRight(insertNode); + return insertNode; + } + currentNode=currentNode.right; + } + } + return new BinaryTreeNode(o); + }*/ + + /* + * 递归实现 + */ + public BinaryTreeNode insert(Comparable o){ + + Comparable data=(Comparable) this.getData(); + int result=data.compareTo(o); + + if(result == 0){ + return this; + }else if(result > 0){ + if(this.getLeft()==null){ + BinaryTreeNode node=new BinaryTreeNode(o); + this.setLeft(node); + return node; + } + return this.getLeft().insert(o); + }else{ + if(this.getRight()==null){ + BinaryTreeNode node=new BinaryTreeNode(o); + this.setRight(node); + return node; + } + return this.getRight().insert(o); + } + } + + public Object getData() { + return data; + } + + public void setData(Comparable data) { + this.data = data; + } + + public BinaryTreeNode getLeft() { + return left; + } + + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + + public BinaryTreeNode getRight() { + return right; + } + + public void setRight(BinaryTreeNode right) { + this.right = right; + } + +} diff --git a/group26/1515345281/src/week1/collection/Iterator.java b/group26/1515345281/src/week1/collection/Iterator.java new file mode 100644 index 0000000000..03e50730f7 --- /dev/null +++ b/group26/1515345281/src/week1/collection/Iterator.java @@ -0,0 +1,5 @@ +package week1.collection; +public interface Iterator{ + public boolean hasNext(); + public Object next(); +} \ No newline at end of file diff --git a/group26/1515345281/src/week1/collection/LinkedList.java b/group26/1515345281/src/week1/collection/LinkedList.java new file mode 100644 index 0000000000..fd0b9c76dd --- /dev/null +++ b/group26/1515345281/src/week1/collection/LinkedList.java @@ -0,0 +1,214 @@ +package week1.collection; + +/* + * 要求:单向链表实现 + */ +public class LinkedList implements List { + + private int size=0;//表示该链表的长度 + private Node head;//链表的头元素 + + public void add(Object o){ + if(null == head){ + head = new Node(o); + size++; + return ; + } + + Node node=head; + while(null != node.next){ + node=node.next; + } + Node addNode=new Node(o); + node.next=addNode; + size++; + } + + public void add(int index , Object o){ + if(size == 0 || index ==size){ + add(o); + return ; + } + + ListUtils.checkIndexRange(index, size); + + if(index==0){ + Node node=new Node(head.next.data); + node.next=head.next; + head.next=node; + head.data=o; + size++; + return ; + } + + Node node=head; + for(int i=0;i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} \ No newline at end of file diff --git a/group26/1515345281/src/week1/collection/List.java b/group26/1515345281/src/week1/collection/List.java new file mode 100644 index 0000000000..013956e25b --- /dev/null +++ b/group26/1515345281/src/week1/collection/List.java @@ -0,0 +1,9 @@ +package week1.collection; + +public interface List{ + public void add(Object o); + public void add(int index,Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} \ No newline at end of file diff --git a/group26/1515345281/src/week1/collection/ListUtils.java b/group26/1515345281/src/week1/collection/ListUtils.java new file mode 100644 index 0000000000..3ebb559aea --- /dev/null +++ b/group26/1515345281/src/week1/collection/ListUtils.java @@ -0,0 +1,9 @@ +package week1.collection; + +public class ListUtils { + + public static void checkIndexRange(int index, int size) { + if (index < 0 || index > size) + throw new IndexOutOfBoundsException(); + } +} diff --git a/group26/1515345281/src/week1/collection/Queue.java b/group26/1515345281/src/week1/collection/Queue.java new file mode 100644 index 0000000000..06f5ea52c8 --- /dev/null +++ b/group26/1515345281/src/week1/collection/Queue.java @@ -0,0 +1,24 @@ +package week1.collection; + +public class Queue { + + private LinkedList list=new LinkedList(); + + public void enQueue(Object o){ + list.add(o); + } + + public Object deQueue(){ + + return list.removeFirst(); + } + + public boolean isEmpty(){ + + return list.size()==0; + } + + public int size(){ + return list.size(); + } +} diff --git a/group26/1515345281/src/week1/collection/Stack.java b/group26/1515345281/src/week1/collection/Stack.java new file mode 100644 index 0000000000..63b226dca8 --- /dev/null +++ b/group26/1515345281/src/week1/collection/Stack.java @@ -0,0 +1,37 @@ +package week1.collection; + +import java.util.EmptyStackException; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + if(isEmpty()){ + throw new EmptyStackException(); + } + + Object data=elementData.get(size()-1); + elementData.remove(size()-1); + return data; + } + + public Object peek(){ + return (Object)elementData.get(size()-1); + } + + public boolean isEmpty(){ + if(elementData.size()==0) + return true; + else + return false; + } + + public int size(){ + return elementData.size(); + } +} diff --git a/group26/1515345281/src/week1/collection/test/ArrayListTest.java b/group26/1515345281/src/week1/collection/test/ArrayListTest.java new file mode 100644 index 0000000000..0fa7701041 --- /dev/null +++ b/group26/1515345281/src/week1/collection/test/ArrayListTest.java @@ -0,0 +1,69 @@ +package week1.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.ArrayList; +import week1.collection.Iterator; + +public class ArrayListTest { + + private ArrayList list=new ArrayList(); + + @Test + public void testAddObject(){ + list.add(1); + assertEquals(1 , list.get(0)); + } + + @Test + public void testAddIndexObject(){ + list.add("aa"); + list.add("bb"); + list.add(0,"cc"); + assertEquals("cc",list.get(0)); + try{ + list.add(-1,"pp"); + fail("- can't be index"); + + list.add(list.size()+100,"bb"); + fail("index should <= size"); + + }catch(Exception ex){ + + } + } + + @Test + public void testGetObject(){ + list.add(1); + assertEquals(1,list.get(0)); + } + + @Test + public void testRemoveObject(){ + list.add(1); + list.add(2); + list.add(3); + list.remove(0); + list.remove(2); + assertEquals(2,list.get(0)); + } + + @Test + public void testSize(){ + assertEquals(0,list.size()); + } + + @Test + public void testIterator(){ + list.add(1); + list.add(2); + list.add(3); + Iterator it=list.iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + } +} diff --git a/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java b/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java new file mode 100644 index 0000000000..a6ea1cac3f --- /dev/null +++ b/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java @@ -0,0 +1,23 @@ +package week1.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.BinaryTreeNode; + +public class BinarySearchTreeTest { + + private BinaryTreeNode root=new BinaryTreeNode(5); + + @Test + public void testInsert(){ + root.insert(2); + root.insert(2); + root.insert(7); + root.insert(1); + root.insert(4); + root.insert(3); + assertEquals(3,root.getLeft().getRight().getLeft().getData()); + } +} diff --git a/group26/1515345281/src/week1/collection/test/LinkedListTest.java b/group26/1515345281/src/week1/collection/test/LinkedListTest.java new file mode 100644 index 0000000000..cba45c719d --- /dev/null +++ b/group26/1515345281/src/week1/collection/test/LinkedListTest.java @@ -0,0 +1,90 @@ +package week1.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Iterator; +import week1.collection.LinkedList; + +public class LinkedListTest { + + private LinkedList list=new LinkedList(); + + @Test + public void testAdd(){ + list.add("1"); + list.add("2"); + list.add("3"); + assertEquals("1",list.get(0)); + assertEquals("2",list.get(1)); + assertEquals(3,list.size()); + } + + @Test + public void testAddByIndex(){ + list.add(2); + list.add(4); + list.add(6); + list.add(0,0); + list.add(3,3); + list.add(5,7); + assertEquals(0, list.get(0)); + assertEquals(3, list.get(3)); + assertEquals(7, list.get(5)); + try{ + list.add(-1,0); + fail("-1 not a correctly index"); + }catch(Exception ex){ + + } + } + + @Test + public void testGet(){ + list.add(0); + list.add(1); + list.add(2); + assertEquals(0,list.get(0)); + } + + @Test + public void testRemove(){ + list.add(0); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + assertEquals(0,list.remove(0)); + assertEquals(4,list.remove(3)); + assertEquals(2,list.remove(1)); + } + + @Test + public void testSize(){ + list.add(0); + list.addLast(0); + list.addFirst(0); + list.remove(0); + list.removeLast(); + list.removeFirst(); + assertEquals(0,list.size()); + } + + @Test + public void testOther(){ + list.add(1); + list.add(1); + list.add(1); + list.add(1); + list.addFirst(0); + list.addLast(2); + list.removeFirst(); + list.removeLast(); + Iterator it=list.iterator(); + while(it.hasNext()){ + System.out.print(it.next()+" "); + } + } + +} diff --git a/group26/1515345281/src/week1/collection/test/QueueTest.java b/group26/1515345281/src/week1/collection/test/QueueTest.java new file mode 100644 index 0000000000..81979682a6 --- /dev/null +++ b/group26/1515345281/src/week1/collection/test/QueueTest.java @@ -0,0 +1,27 @@ +package week1.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Queue; + +public class QueueTest { + + private Queue queue=new Queue(); + + @Test + public void testEnQueue(){ + queue.enQueue("123"); + queue.enQueue("456"); + assertEquals("123",queue.deQueue()); + } + + @Test + public void testDeQueue(){ + queue.enQueue("123"); + queue.enQueue("456"); + queue.deQueue(); + assertEquals("456",queue.deQueue()); + } +} diff --git a/group26/1515345281/src/week1/collection/test/StackTest.java b/group26/1515345281/src/week1/collection/test/StackTest.java new file mode 100644 index 0000000000..717bf9b6a8 --- /dev/null +++ b/group26/1515345281/src/week1/collection/test/StackTest.java @@ -0,0 +1,56 @@ +package week1.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Stack; + +public class StackTest { + + private Stack stack=new Stack(); + + @Test + public void testPush(){ + stack.push("hello"); + stack.push("world"); + assertEquals("world",stack.peek()); + } + + @Test + public void testPop(){ + stack.push("hello"); + stack.push("world"); + assertEquals("world",stack.pop()); + assertEquals(1,stack.size()); + } + + @Test + public void testPeek(){ + stack.push("world"); + assertEquals("world",stack.peek()); + stack.pop(); + try{ + stack.peek(); + fail("stack is empty,can't do peek"); + + }catch(Exception ex){ + + } + } + + @Test + public void testEmpty(){ + assertEquals(true,stack.isEmpty()); + stack.push("hello"); + stack.push("world"); + assertEquals(false,stack.isEmpty()); + } + + @Test + public void testSize(){ + stack.push("hello"); + stack.pop(); + assertEquals(0,stack.size()); + } +} diff --git a/group26/1515345281/src/week2/arrayutil/ArrayUtil.java b/group26/1515345281/src/week2/arrayutil/ArrayUtil.java new file mode 100644 index 0000000000..dcc530949d --- /dev/null +++ b/group26/1515345281/src/week2/arrayutil/ArrayUtil.java @@ -0,0 +1,225 @@ +package week2.arrayutil; + +import java.util.ArrayList; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + for(int i=0;i list=new ArrayList(); + int i=0; + int j=0; + while(i array2[j]){ + list.add(array2[j]); + j++; + }else{ + list.add(array1[i]); + i++; + j++; + } + } + while(i=result.length ){ + result=this.grow(result, 5); + } + result[cursor]=result[cursor-2]+result[cursor-1]; + cursor++; + } + return result; + } + + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max<=1){ + return new int[0]; + } + if(max == 2){ + return new int[]{2}; + } + + int[] temp=new int[max]; + temp[2]=2; + int primeNum=0; + for(int i=3;i list=new ArrayList(); + for(int i=6;i parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + - + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + + return null; + } + +} diff --git a/group26/1515345281/src/week2/struts2/StrutsTest.java b/group26/1515345281/src/week2/struts2/StrutsTest.java new file mode 100644 index 0000000000..68ec3ee4b4 --- /dev/null +++ b/group26/1515345281/src/week2/struts2/StrutsTest.java @@ -0,0 +1,40 @@ +package week2.struts2; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group26/1515345281/src/week2/struts2/View.java b/group26/1515345281/src/week2/struts2/View.java new file mode 100644 index 0000000000..5a907a455f --- /dev/null +++ b/group26/1515345281/src/week2/struts2/View.java @@ -0,0 +1,23 @@ +package week2.struts2; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group26/1515345281/src/week2/struts2/struts.xml b/group26/1515345281/src/week2/struts2/struts.xml new file mode 100644 index 0000000000..9e69fa4e47 --- /dev/null +++ b/group26/1515345281/src/week2/struts2/struts.xml @@ -0,0 +1,12 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group26/1778842360/first heomework/src/ArrayList.java b/group26/1778842360/first heomework/src/ArrayList.java new file mode 100644 index 0000000000..79c83046be --- /dev/null +++ b/group26/1778842360/first heomework/src/ArrayList.java @@ -0,0 +1,149 @@ + +//package javaTest; + +import java.util.Arrays; + +public class ArrayList { + + private Object[] elementData=new Object[2]; + int size; + //Ԫ + public void add(Object o) + { + if(sizei;x--) + { + if(x==index+1) + { + elementData[x]=t; + } + else + { + elementData[x]=elementData[x-1]; + } + + } + } + } + } + public Iterator iterator() + { + return new ArrayListIterator(this); + } + private class ArrayListIterator implements Iterator + { + ArrayList l=null; + int pos=0; + private ArrayListIterator(ArrayList l) + { + this.l=l; + } + public boolean hasNext() { + // TODO Auto-generated method stub + boolean flag=true; + pos++; + if(pos>size) + { + flag=false; + } + return flag; + } + + public Object next() { + // TODO Auto-generated method stub + + return elementData[pos-1]; + } + } + + + + +} + diff --git a/group26/1778842360/first heomework/src/ArrayTest.java b/group26/1778842360/first heomework/src/ArrayTest.java new file mode 100644 index 0000000000..4a5a9eabe5 --- /dev/null +++ b/group26/1778842360/first heomework/src/ArrayTest.java @@ -0,0 +1,27 @@ + +//package javaTest; + +public class ArrayTest { + + /** + * @param args + * ģArrayListʵֶԪصɾ + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + ArrayList a=new ArrayList(); + a.add("hello"); + a.add("java"); + a.add("world"); + a.add("hello"); + // a.add(2,"hello"); + Iterator it=a.iterator(); + while(it.hasNext()) + { + System.out.print(it.next()+" "); + } + System.out.println(a.size()); + } + +} + diff --git a/group26/1778842360/first heomework/src/BinaryTreeNode.java b/group26/1778842360/first heomework/src/BinaryTreeNode.java new file mode 100644 index 0000000000..b5e788838e --- /dev/null +++ b/group26/1778842360/first heomework/src/BinaryTreeNode.java @@ -0,0 +1,34 @@ + +//package com.coding.basic; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} + diff --git a/group12/495473393/Coding/src/Base/Iterator.java b/group26/1778842360/first heomework/src/Iterator.java similarity index 85% rename from group12/495473393/Coding/src/Base/Iterator.java rename to group26/1778842360/first heomework/src/Iterator.java index 19b65c3637..dbb092f46e 100644 --- a/group12/495473393/Coding/src/Base/Iterator.java +++ b/group26/1778842360/first heomework/src/Iterator.java @@ -1,6 +1,6 @@ -package Base; public interface Iterator { + public boolean hasNext(); public Object next(); diff --git a/group26/1778842360/first heomework/src/LinkedList.java b/group26/1778842360/first heomework/src/LinkedList.java new file mode 100644 index 0000000000..0f63676418 --- /dev/null +++ b/group26/1778842360/first heomework/src/LinkedList.java @@ -0,0 +1,209 @@ +//package com.coding.basic; + +public class LinkedList implements List { + + private Node head; + int size; + public void add(Object o){ + if(head==null) + { + head=new Node(o); + head.next=null; + head.data=o; + } + else{ + Node p=head; + { + while(p.next!=null) + { + p=p.next; + } + Node n=new Node(o); + p.next=n; + n.data=o; + n.next=null; + } + } + size++; + } + public void add(int index , Object o){ + int i=1; + Node p=head; + while(iindex) {return null;} + return p.data; + } + public Object remove(int index){ + int i=1; + Node p=head; + Object o=null; + if(index==1) + { + o=head.data; + if(head.next!=null) + { + p=head.next; + head.data=p.data; + p=head; + } + else{ + head=null; + } + } + else{ + while(i0) + { + flag=false; + } + return flag; + } + + public int size(){ + return l.size; + } +} + diff --git a/group26/1778842360/first heomework/src/QueueTest.java b/group26/1778842360/first heomework/src/QueueTest.java new file mode 100644 index 0000000000..81131511c9 --- /dev/null +++ b/group26/1778842360/first heomework/src/QueueTest.java @@ -0,0 +1,21 @@ + +//package com.coding.basic; + +public class QueueTest { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Queue q=new Queue(); + q.enQueue("add"); + q.enQueue("world"); + int length=q.size(); + System.out.println(length); + System.out.println(q.deQueue()); + System.out.println(q.isEmpty()); + } + +} + diff --git a/group26/1778842360/first heomework/src/Stack.java b/group26/1778842360/first heomework/src/Stack.java new file mode 100644 index 0000000000..20cdba1c4b --- /dev/null +++ b/group26/1778842360/first heomework/src/Stack.java @@ -0,0 +1,35 @@ + +//package javaTest; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + //Ԫѹջ + public void push(Object o){ + elementData.add(o); + } + //Ԫسջ + public Object pop(){ + Object o=elementData.remove(elementData.size-1); + return o; + } + //ȡջԪ + public Object peek(){ + Object o=elementData.get(elementData.size-1); + return o; + } + //жջǷΪ + public boolean isEmpty(){ + boolean flag=true; + if(elementData.size>0) + { + flag=false; + } + return flag; + } + //ȡջĴС + public int size(){ + return elementData.size; + } +} + diff --git a/group26/1778842360/first heomework/src/StackTest.java b/group26/1778842360/first heomework/src/StackTest.java new file mode 100644 index 0000000000..271ba04daf --- /dev/null +++ b/group26/1778842360/first heomework/src/StackTest.java @@ -0,0 +1,24 @@ +//package javaTest; + +public class StackTest { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Stack s=new Stack(); + s.push("world"); + s.push("java"); + s.push("world"); + Object o1=s.peek(); + System.out.println(o1); + Object o=s.pop(); + System.out.println(o); + int size=s.size(); + System.out.println(size); + System.out.println(s.isEmpty()); + } + +} + diff --git a/group26/1778842360/second homework/ArrayUtil.java b/group26/1778842360/second homework/ArrayUtil.java new file mode 100644 index 0000000000..c9efeb2d0b --- /dev/null +++ b/group26/1778842360/second homework/ArrayUtil.java @@ -0,0 +1,239 @@ +package array; + +import java.util.Arrays; + +public class ArrayUtil { + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public static void reverseArray(int[] origin){ + for(int i=0;iarray2[j]){ + array3[k++]=array2[j]; + j++; + } + else{ + array3[k++]=array1[i]; + i++; + j++; + } + } + while(i -1; i--) + { + tempArrays[j] = origin[i]; + j++; + } + } + + /** + * µһ飺 int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ҪֵΪ0ȥΪ0ֵһµ飬ɵΪ + * {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) + { + // ArrayListҪ֪ȣڴ˴ + List list = new ArrayList(); + for (int i = 0; i < oldArray.length; i++) + { + if (oldArray[i] != 0) + { + list.add(oldArray[i]); + } + } + int[] newArray = new int[list.size()]; + for (int i = 0; i < list.size(); i++) + { + newArray[i] = list.get(i); + } + return newArray; + + } + + /** + * Ѿõ飬 a1a2 , һµa3, ʹa3 a1a2 Ԫأ Ȼ a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] a3 + * Ϊ[3,4,5,6,7,8] , ע⣺ Ѿظ + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) + { + //Setϲظֵ + Set set = new HashSet(); + for (int i : array1) + { + set.add(i); + } + for (int i : array2) + { + set.add(i); + } + int[] newArr = new int[set.size()]; + Iterator it = set.iterator(); + int i = 0; + while (it.hasNext()) + { + newArr[i] = it.next(); + i++; + } + // newArrð + for (int j = 0; j < newArr.length - 1; j++) + { + for (int k = 0; k < newArr.length - 1 - j; k++) + { + int temp = 0; + if (newArr[k] > newArr[k + 1]) + { + temp = newArr[k]; + newArr[k + 1] = temp; + } + } + } + return newArr; + } + + /** + * һѾݵ oldArrayչ չݴСΪoldArray.length + size ע⣬ԪҪ oldArray = [2,3,6] , size = + * 3,򷵻صΪ [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) + { + int[] newArray = Arrays.copyOf(oldArray, oldArray.length + size); + return newArray; + } + + /** + * 쳲Ϊ1123581321...... һֵ Сڸֵ 磬 max = 15 , 򷵻صӦΪ [11235813] max = 1, 򷵻ؿ [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) + { + // f(n)=f(n-1)+f(n-2) + // f(0)=1 f(1)=1 f(2)=f(0)+f(1)=2 + List list = new ArrayList(); + int[] newArr = null; + if (max == 1) + return newArr; + int num = 0; + int x = 1, y = 1; + list.add(1);// f(0)=1; + list.add(1);// f(1)=1; + while (true) + { + num = x + y; + x = y; + y = num; + if (num >= max) + break; + list.add(num); + } + newArr = new int[list.size()]; + for (int k = 0; k < list.size(); k++) + { + newArr[k] = list.get(k); + } + return newArr; + } + + /** + * 쳲еĵݹ㷨 + * + * @param i + * @return + */ + public static int getFiboo(int i) + { + if (i == 1 || i == 2) + return 1; + else + return getFiboo(i - 1) + getFiboo(i - 2); + } + + /** + * Сڸֵmax max = 23, صΪ[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) + { + int[] newArr = null; + List list = new ArrayList(); + for (int i = 1; i < max; i++) + { + boolean flag = isPrime(i); + if (flag) + list.add(i); + } + newArr = new int[list.size()]; + for (int k = 0; k < list.size(); k++) + { + newArr[k] = list.get(k); + } + return newArr; + } + + public static boolean isPrime(int n) + { + if (n == 1) + return false; + if (n == 2) + return true; + if (n % 2 == 0) + return false;// ż϶ + for (int i = 3; i < n; i += 2)// ȥżж + { + if (n % i == 0) + return false; + } + return true; + } + + /** + * ν ָǡõ֮ͣ6=1+2+3 һֵmax һ飬 Сmax + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) + { + List list = new ArrayList(); + List factorList = null; + for (int i = 1; i < max; i++) + { + // е + if (isPrime(i)) + { + continue; + } + factorList = getFactor(i); + int count = 0; + for (int j = 0; j < factorList.size(); j++) + { + count += factorList.get(j); + } + if (count != i) + continue; + list.add(i); + } + int[] newArr = new int[list.size()]; + for (int k = 0; k < list.size(); k++) + { + newArr[k] = list.get(k); + } + return newArr; + } + + /** + * һ + **/ + public static List getFactor(int number) + { + List list = new ArrayList(); + for (int i = 1; i < number; i++) + { + if (number % i != 0) + continue; + list.add(i); + } + return list; + } + + /** + * seperator array array= [3,8,9], seperator = "-" 򷵻ֵΪ"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) + { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < array.length; i++) + { + if (i == array.length - 1) + { + sb.append(array[i]); + break; + } + sb.append(array[i] + seperator); + } + return sb.toString(); + } + +} \ No newline at end of file diff --git a/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java b/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java new file mode 100644 index 0000000000..a8bad2d7df --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java @@ -0,0 +1,52 @@ +package week2.com.coding.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * + * @author liuxin + * + */ +public class LoginAction +{ + private String name; + + private String password; + + private String message; + + public String getName() + { + return name; + } + + public String getPassword() + { + return password; + } + + public String execute() + { + if ("test".equals(name) && "1234".equals(password)) + { + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name) + { + this.name = name; + } + + public void setPassword(String password) + { + this.password = password; + } + + public String getMessage() + { + return this.message; + } +} diff --git a/group26/191191717/src/week2/com/coding/litestruts/Struts.java b/group26/191191717/src/week2/com/coding/litestruts/Struts.java new file mode 100644 index 0000000000..e9b902c518 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/Struts.java @@ -0,0 +1,156 @@ +package week2.com.coding.litestruts; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +public class Struts +{ + + public static View runAction(String actionName, Map parameters) + { + + /* + * + * 0. 读取配置文件struts.xml + * + * 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + * ("name"="test" , "password"="1234") , 那就应该调用 setName和setPassword方法 + * + * 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + * + * 3. 通过反射找到对象的所有getter方法(例如 getMessage), 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + * 放到View对象的parameters + * + * 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, 放到View对象的jsp字段中。 + * + */ + File file = new File("src/week2/com/coding/litestruts/struts.xml"); + resolveXml(file); + Object object = actions.get(actionName); + Set set = parameters.keySet();// 获取键值 + Iterator it = set.iterator(); + View view = new View(); + try + { + while (it.hasNext()) + { + String keyName = it.next(); + String setMethodName = "set" + keyName.substring(0, 1).toUpperCase() + keyName.substring(1);// 组合方法名 + + Method method = object.getClass().getMethod(setMethodName, String.class); + if (method == null) + { + continue; + } + method.invoke(object, parameters.get(keyName));// 执行set方法 + } + + Method exeMethod = object.getClass().getMethod("execute"); + String result = (String)exeMethod.invoke(object);// 获取execute方法返回值 + // 获取对象所有的属性值 + Field[] fs = object.getClass().getDeclaredFields(); + HashMap resultMap = new HashMap(); + for (Field f : fs) + { + String fieldName = f.getName(); + Method m2 = object.getClass() + .getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)); + String rs2 = (String)m2.invoke(object); + // 将所有get方法的返回值存入map + resultMap.put(fieldName, rs2); + } + view.setParameters(resultMap); + // 根据result的值找到xml配置的值 + if (null != result) + { + String viewURL = (String)actions.get(actionName + "_" + result); + view.setJsp(viewURL); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + return view; + } + + static Map actions = new HashMap(); + + /** + * 解析XML,将xml映射对象,以及返回值的属性存入actions + * + * @param file + */ + @SuppressWarnings("unchecked") + public static void resolveXml(File file) + { + SAXReader read = new SAXReader(); + Element rootElement = null; + try + { + rootElement = read.read(file).getRootElement(); + List actionList = rootElement.elements("action"); + for (Element ele : actionList) + { + String name = ele.attributeValue("name"); + String clz = ele.attributeValue("class");// 找到类名 + Object obj = Class.forName(clz).newInstance(); + actions.put(name, obj); + if (ele.hasContent())// 如果还有节点 + { + List list = ele.elements("result"); + for (Element e : list) + { + String cName = e.attributeValue("name"); + String cValue = e.getTextTrim(); + actions.put(name + "_" + cName, cValue);// 示例key:login_success + } + } + } + } + catch (DocumentException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + public static void main(String[] args) + throws Exception + { + File file = new File("src/week2/com/coding/litestruts/struts.xml"); + resolveXml(file); + System.out.println(actions.toString()); + // Map parameters = new HashMap(); + // parameters.put("name", "luojunyi"); + // runAction("login", parameters); + // Class clazz = Class.forName("week2.com.coding.litestruts.LoginAction"); + // Object obj = clz.newInstance(); + // System.out.println(obj.toString()); + // Method m1 = clz.getMethod("setName", java.lang.String.class); + // System.out.println(m1.getName()); + // m1.invoke(obj, "hello"); + // Method m2 = clz.getMethod("getName"); + // System.out.println(m2.getName()); + // String s = (String)m2.invoke(obj); + // System.out.println(s); + // Field[] f = clazz.getDeclaredFields(); + // for (int i = 0; i < f.length; i++) + // { + // System.out.println(f[i].getName()); + // } + } +} diff --git a/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java b/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java new file mode 100644 index 0000000000..7f5125c107 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java @@ -0,0 +1,41 @@ +package week2.com.coding.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class StrutsTest +{ + + @Test + public void testLoginActionSuccess() + { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name", "test"); + params.put("password", "1234"); + + View view = Struts.runAction(actionName, params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() + { + String actionName = "login"; + Map params = new HashMap(); + params.put("name", "test"); + params.put("password", "123456"); // //密码和预设的不一致 + + View view = Struts.runAction(actionName, params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group26/191191717/src/week2/com/coding/litestruts/View.java b/group26/191191717/src/week2/com/coding/litestruts/View.java new file mode 100644 index 0000000000..3d0708b0c0 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/View.java @@ -0,0 +1,23 @@ +package week2.com.coding.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group26/191191717/src/week2/com/coding/litestruts/struts.xml b/group26/191191717/src/week2/com/coding/litestruts/struts.xml new file mode 100644 index 0000000000..d63e7651d8 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + \ No newline at end of file diff --git a/group26/191191717/src/week2/com/coding/test/ArrayUtilTest.java b/group26/191191717/src/week2/com/coding/test/ArrayUtilTest.java new file mode 100644 index 0000000000..d0ba653c37 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/test/ArrayUtilTest.java @@ -0,0 +1,89 @@ +package week2.com.coding.test; + +import static org.junit.Assert.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import week2.com.coding.basic.ArrayUtil; + +public class ArrayUtilTest +{ + private static ArrayUtil arrayUtil = null; + + @Before + public void init() + { + arrayUtil = new ArrayUtil(); + } + + @Test + public void testReverseArray() + { + int[] arrays = {7, 9, 30, 3}; + arrayUtil.reverseArray(arrays); + } + + @Test + public void testRemoveZero() + { + int oldArr[] = {1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5}; + int newArr[] = {1, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5}; + Assert.assertArrayEquals(newArr, arrayUtil.removeZero(oldArr)); + } + + @Test + public void testMerge() + { + int[] array1 = {3, 5, 7, 8}; + int[] array2 = {4, 5, 6, 7}; + int[] vaildateArr = {3, 4, 5, 6, 7, 8}; + int[] arrs = arrayUtil.merge(array1, array2); + Assert.assertArrayEquals(vaildateArr, arrs); + } + + @Test + public void testGrow() + { + int[] vaildateArr = {2, 3, 6, 0, 0, 0}; + int[] oldArr = {2, 3, 6}; + int[] arrs = arrayUtil.grow(oldArr, 3); + Assert.assertArrayEquals(vaildateArr, arrs); + + } + + @Test + public void testFibonacci() + { + int [] validateArr={1,1,2,3,5,8,13}; + int [] newArr=arrayUtil.fibonacci(15); + Assert.assertArrayEquals(validateArr, newArr); + } + + @Test + public void testGetPrimes() + { + int[] arrs = arrayUtil.getPrimes(23); + for (int i : arrs) + System.out.printf("%d ", i); + } + + @Test + public void testGetPerfectNumbers() + { + int [] validateArr={6,28}; + int [] newArr=arrayUtil.getPerfectNumbers(100); + Assert.assertArrayEquals(validateArr, newArr); + } + + @Test + public void testJoin() + { + String validateStr = "3-8-9"; + int[] oldArr = {3, 8, 9}; + String str = arrayUtil.join(oldArr, "-"); + Assert.assertEquals(validateStr, str); + } + +} diff --git "a/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" "b/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" index 78f2236da7..165922cc87 100644 --- "a/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" +++ "b/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" @@ -5,15 +5,17 @@ | | 文章1 | | | | | | 723161901 | 已完成 | | | | | | | | | | | | -| jiaxun1990(89460886) | 已完成 | | | | | +| jiaxun1990(89460886) | 已完成 | 已完成 | | | | | | https://goo.gl/Wvz3Od | | | | | -| 1515345281 | 已完成 | | | | | +| 1515345281 | 已完成 | 已完成 | | | | | | | | | | | | 2070509107 | 已完成 | | | | | | | | | | | | -| lizhy2017 | 部分完成 | | | | | +| lizhy2017 | 部分完成 | 已完成 | | | | | | | | | | | | JEE-逆水百川 | 部分完成 | | | | | | | http://blog.csdn.net/u012759397/article/details/61618612 | | | | | -|191191717 |已完成|       |           |     |     |     |     |     |     |     | +|191191717 |已完成|   已完成    |           |     |     |     |     |     |     |     | | | | | | | | | | | | | +| 1778842360 | 已完成 |完成80% | | | | | | | | | +| | 文章1 http://note.youdao.com/noteshare?id=7e8faf2bd2a7a3e5259d83bb1e6d9d8f | | | | | | | | | | diff --git a/group26/89460886/src/week02/.DS_Store b/group26/89460886/src/week02/.DS_Store new file mode 100644 index 0000000000..5008ddfcf5 Binary files /dev/null and b/group26/89460886/src/week02/.DS_Store differ diff --git a/group26/89460886/src/week02/source/ArrayUtil.java b/group26/89460886/src/week02/source/ArrayUtil.java new file mode 100644 index 0000000000..c9f069c019 --- /dev/null +++ b/group26/89460886/src/week02/source/ArrayUtil.java @@ -0,0 +1,190 @@ +package coding; + +import java.util.Arrays; + +/** + * @author jiaxun + */ +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + if (origin == null) return; + int length = origin.length; + for (int i = 0, middle = length / 2; i < middle; i++) { + int temp = origin[i]; + origin[i] = origin[length - i - 1]; + origin[length - i - 1] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + if (oldArray == null) return null; + int[] newArray = new int[oldArray.length]; + int count = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + newArray[count++] = oldArray[i]; + } + } + return Arrays.copyOf(newArray, count); + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + int len1 = array1.length; + int len2 = array2.length; + int[] array3 = new int[len1 + len2]; + int arr1Index = 0, arr2Index = 0, arr3Index = 0, zeroCount = 0; + while (arr1Index < len1 && arr2Index < len2) { + if (array1[arr1Index] < array2[arr2Index]) { + array3[arr3Index++] = array1[arr1Index++]; + } else if (array1[arr1Index] > array2[arr2Index]) { + array3[arr3Index++] = array2[arr2Index++]; + } else { + array3[arr3Index++] = array1[arr1Index++] = array2[arr2Index++]; + zeroCount++; + } + } + while (arr1Index < len1) { + array3[arr3Index++] = array1[arr1Index++]; + } + while (arr2Index < len2) { + array3[arr3Index++] = array2[arr2Index++]; + } + return Arrays.copyOf(array3, len1 + len2 - zeroCount); + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return Arrays.copyOf(oldArray, oldArray.length + size); + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + if (max == 1) return null; + int first = 1, second = 1; + int next = 2; + int[] result = new int[max]; + result[0] = first; result[1] = second; + int count = 2; + while (next < max) { + result[count++] = next; + first = second; + second = next; + next = first + second; + } + return Arrays.copyOf(result, count); + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if (max <= 2) return null; + int [] result = new int[max]; + int count = 0; + for (int i = 2; i < max; i++) { + if (!primes(i)) { + result[count++] = i; + } + } + return Arrays.copyOf(result, count); + } + + private boolean primes(int data) { + int sqrt = (int) Math.sqrt(data) + 1; + for (int i = 2; i < sqrt; i++) { + if (data % i == 0){ + return true; + } + } + return false; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + int[] result = new int[max - 2]; + int count = 0; + for (int i = 2; i < max; i++) { + if (perfectNumber(i)) + result[count++] = i; + } + return Arrays.copyOf(result, count); + } + + private boolean perfectNumber(int number) { + int left = 2, right = number; + int sum = 1; + while (left < right) { + if (number % left == 0) { + sum += left; + right = number / left; + if (left != right) sum += right; + } + left++; + } + return sum == number; + } + + /** + * 用separator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param separator + * @return + */ + public String join(int[] array, String separator){ + if (array == null) return null; + StringBuilder result = new StringBuilder(); + result.append(array[0]); + for (int i = 1, len = array.length; i < len; i++) { + result.append(separator).append(array[i]); + } + return result.toString(); + } + +} diff --git a/group26/89460886/src/week02/source/struts/.DS_Store b/group26/89460886/src/week02/source/struts/.DS_Store new file mode 100644 index 0000000000..5008ddfcf5 Binary files /dev/null and b/group26/89460886/src/week02/source/struts/.DS_Store differ diff --git a/group26/89460886/src/week02/source/struts/Action.java b/group26/89460886/src/week02/source/struts/Action.java new file mode 100644 index 0000000000..fd71d5693a --- /dev/null +++ b/group26/89460886/src/week02/source/struts/Action.java @@ -0,0 +1,10 @@ +package coding.coderising.litestruts; + +/** + * @author jiaxun + */ +public interface Action { + + String execute(); + +} diff --git a/group26/89460886/src/week02/source/struts/Constants.java b/group26/89460886/src/week02/source/struts/Constants.java new file mode 100644 index 0000000000..62e7889dd1 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/Constants.java @@ -0,0 +1,12 @@ +package coding.coderising.litestruts; + +/** + * @author jiaxun + */ +public class Constants { + + public static final String ACTION_SUCCESS = "success"; + public static final String ACTION_FAILURE = "failure"; + public static final String ACTION_ERROR = "error"; + +} diff --git a/group26/89460886/src/week02/source/struts/DOMParser.java b/group26/89460886/src/week02/source/struts/DOMParser.java new file mode 100644 index 0000000000..77669774e9 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/DOMParser.java @@ -0,0 +1,27 @@ +package coding.coderising.litestruts; + +import org.w3c.dom.Document; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; + +/** + * @author jiaxun + */ +public class DOMParser { + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + + public Document parse(String filePath) { + Document document = null; + try { + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(new File(filePath)); + } catch (Exception e) { + e.printStackTrace(); + } + return document; + } + +} diff --git a/group26/89460886/src/week02/source/struts/LoginAction.java b/group26/89460886/src/week02/source/struts/LoginAction.java new file mode 100644 index 0000000000..50aa12d71a --- /dev/null +++ b/group26/89460886/src/week02/source/struts/LoginAction.java @@ -0,0 +1,48 @@ +package coding.coderising.litestruts; + +/** + * @author jiaxun + */ +public class LoginAction implements Action { + + private String name; + private String password; + private String message; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String execute() { + if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(password) && + "test".equals(name) && "1234".equals(password)) { + message = "login successful"; + return Constants.ACTION_SUCCESS; + } else { + message = "login failed,please check your user/pwd"; + return Constants.ACTION_FAILURE; + } + } + +} diff --git a/group26/89460886/src/week02/source/struts/LogoutAction.java b/group26/89460886/src/week02/source/struts/LogoutAction.java new file mode 100644 index 0000000000..d2bfc5c477 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/LogoutAction.java @@ -0,0 +1,7 @@ +package coding.coderising.litestruts; + +/** + * @author jiaxun + */ +public class LogoutAction { +} diff --git a/group26/89460886/src/week02/source/struts/StringUtils.java b/group26/89460886/src/week02/source/struts/StringUtils.java new file mode 100644 index 0000000000..37e7afcad1 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/StringUtils.java @@ -0,0 +1,12 @@ +package coding.coderising.litestruts; + +/** + * @author jiaxun + */ +public class StringUtils { + + public static boolean isEmpty(CharSequence str) { + return str == null || str.length() == 0; + } + +} diff --git a/group26/89460886/src/week02/source/struts/Struts.java b/group26/89460886/src/week02/source/struts/Struts.java new file mode 100644 index 0000000000..49fc38d077 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/Struts.java @@ -0,0 +1,92 @@ +package coding.coderising.litestruts; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +/** + * @author jiaxun + */ +public class Struts { + + public static View runAction(String actionName, Map parameters) { + if (StringUtils.isEmpty(actionName)) return null; + DOMParser parser = new DOMParser(); + Document document = parser.parse("src/coding/coderising/litestruts/struts.xml"); + Element rootElement = document.getDocumentElement(); + + NodeList actionList = rootElement.getElementsByTagName("action"); + if (actionList == null || actionList.getLength() == 0) return null; + + for (int i = 0, len = actionList.getLength(); i < len; i++) { + Element element = (Element) actionList.item(i); + String name = element.getAttribute("name"); + if (actionName.equals(name)) { + return handleAction((Element) actionList.item(i), parameters); + } + } + return null; + } + + private static View handleAction(Element element, Map parameters) { + String className = element.getAttribute("class"); + try { + Class clazz = Class.forName(className); + Object object = clazz.newInstance(); + + for (Map.Entry entry : parameters.entrySet()) { + String methodStr = "set" + entry.getKey().toUpperCase().substring(0, 1) + + entry.getKey().substring(1); + Method method = clazz.getMethod(methodStr, String.class); + method.invoke(object, entry.getValue()); + } + + Method execute = clazz.getMethod("execute"); + String result = (String) execute.invoke(object); + + Map getParams = new HashMap<>(); + Field[] fields = clazz.getDeclaredFields(); + if (fields != null && fields.length > 0) { + for (int i = 0, len = fields.length; i < len; i++) { + PropertyDescriptor pd = new PropertyDescriptor(fields[i].getName(), clazz); + Method getMethod = pd.getReadMethod(); + if (getMethod != null) { + getParams.put(fields[i].getName(), (String) getMethod.invoke(object)); + } + } + } + + NodeList nodeList = element.getElementsByTagName("result"); + for (int i = 0; i < nodeList.getLength(); i++) { + Element resultElement = (Element) nodeList.item(i); + String name = resultElement.getAttribute("name"); + if ("success".equals(name) && Constants.ACTION_SUCCESS.equals(result)) { + return createView(resultElement, getParams); + } + if ("failure".equals(name) && Constants.ACTION_FAILURE.equals(result)) { + return createView(resultElement, getParams); + } + if ("error".equals(name) && Constants.ACTION_ERROR.equals(result)) { + return createView(resultElement, getParams); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private static View createView(Element element, Map parameters) { + View view = new View(); + view.setJsp(element.getTextContent()); + view.setParameters(parameters); + return view; + } + +} diff --git a/group26/89460886/src/week02/source/struts/struts.xml b/group26/89460886/src/week02/source/struts/struts.xml new file mode 100644 index 0000000000..811f2c9134 --- /dev/null +++ b/group26/89460886/src/week02/source/struts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group26/89460886/src/week02/test/TestArrayUtil.java b/group26/89460886/src/week02/test/TestArrayUtil.java new file mode 100644 index 0000000000..836d4366b8 --- /dev/null +++ b/group26/89460886/src/week02/test/TestArrayUtil.java @@ -0,0 +1,95 @@ +import coding.ArrayUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * @author jiaxun + */ +public class TestArrayUtil { + + private ArrayUtil arrayUtil; + + @Before + public void setUp() { + arrayUtil = new ArrayUtil(); + } + + @After + public void tearDown() { + + } + + @Test + public void testReverseArrayOdd() { + int[] actualArray = {6, 2, 5, 8, 7}; + arrayUtil.reverseArray(actualArray); + int[] expectedArray = {7, 8, 5, 2, 6}; + Assert.assertArrayEquals(expectedArray, actualArray); + } + + @Test + public void testReverseArrayEven() { + int[] actualArray = {5, 3, 6, 7}; + arrayUtil.reverseArray(actualArray); + int[] expectedArray = {7, 6, 3, 5}; + Assert.assertArrayEquals(expectedArray, actualArray); + } + + @Test + public void testRemoveZero() { + int[] oldArray = {4, 5, 0, 7, 0, 3}; + int[] newArray = arrayUtil.removeZero(oldArray); + Assert.assertEquals(newArray.length, 4); + Assert.assertEquals(newArray[2], 7); + } + + @Test + public void testMerge() { + int[] array1 = {3, 5, 7,8}; + int[] array2 = {4, 5, 6,7}; + int[] array3 = arrayUtil.merge(array1, array2); + Assert.assertEquals(array3.length, 6); + int[] expectArray = {3, 4, 5, 6, 7, 8}; + Assert.assertArrayEquals(expectArray, array3); + } + + @Test + public void testGrow() { + int[] array = {2, 3, 6}; + int[] result = arrayUtil.grow(array, 3); + Assert.assertEquals(result.length, 6); + int[] expectedArray = {2, 3, 6, 0, 0, 0}; + Assert.assertArrayEquals(expectedArray, result); + } + + @Test + public void testFibonacci() { + int[] result = arrayUtil.fibonacci(15); + int[] expect = {1, 1, 2, 3, 5, 8, 13}; + Assert.assertArrayEquals(expect, result); + } + + @Test + public void testGetPerfectNumbers() { + int[] result = arrayUtil.getPerfectNumbers(500); + int[] expected = {6, 28, 496}; + Assert.assertArrayEquals(expected, result); + } + + @Test + public void testGetPrimes() { + int[] result = arrayUtil.getPrimes(23); + int[] expectedArray = {2, 3, 5, 7, 11, 13, 17, 19}; + Assert.assertArrayEquals(expectedArray, result); + } + + @Test + public void testJoin() { + int[] source = {3,8,9}; + String result = arrayUtil.join(source, "-"); + Assert.assertEquals("3-8-9", result); + } + +} diff --git a/group26/89460886/src/week02/test/TestStruct.java b/group26/89460886/src/week02/test/TestStruct.java new file mode 100644 index 0000000000..69d80d3642 --- /dev/null +++ b/group26/89460886/src/week02/test/TestStruct.java @@ -0,0 +1,44 @@ +package coding.coderising.litestruts; + +import list.Iterator; +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author jiaxun + */ +public class TestStruct { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap<>(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } + +} diff --git a/group26/lizhy2017/homework/second/array/ArrayUtil.java b/group26/lizhy2017/homework/second/array/ArrayUtil.java new file mode 100644 index 0000000000..253356ef7d --- /dev/null +++ b/group26/lizhy2017/homework/second/array/ArrayUtil.java @@ -0,0 +1,206 @@ +package second.array; + +import java.util.Arrays; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + * 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + * 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + */ + public void reverseArray(int[] origin) { + if (null != origin) return; + for (int i = 0; i < origin.length; i++) { + int temp = origin[i]; + origin[i] = origin[origin.length - i - 1]; + origin[i] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + if (null != oldArray) { + return null; + } + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] == 0) { + System.arraycopy(oldArray, i + 1, oldArray, i, oldArray.length - i - 1); + } + } + return oldArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) { + if (null != array1 && null != array2) return null; + int[] temp = new int[array1.length + array2.length]; + int i = 0, j = 0; + if (array1.length >= array2.length) { + while (i < array2.length) { + i++; + if (array1[i] <= array2[i]) + temp[i] = array1[i]; + else + temp[i] = array2[i]; + } + System.arraycopy(array1, i + 1, temp, i + 1, temp.length - i - 1); + } else { + while (j < array1.length) { + j++; + if (array1[j] <= array2[j]) + temp[j] = array1[j]; + else + temp[j] = array2[j]; + } + System.arraycopy(array1, j + 1, temp, j + 1, temp.length - j - 1); + } + return null; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + int oldCapacity = oldArray.length; + int newCapacity = oldCapacity + (oldCapacity >> 1); + if (newCapacity < size) { + newCapacity = size; + } + if (newCapacity > 2147483639) { + newCapacity = 2147483639; + } + return oldArray = Arrays.copyOf(oldArray, newCapacity); + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + if (max <= 1) + return new int[0]; + int[] temp = new int[max]; + temp[0] = 1; + temp[1] = 1; + int last = 1; + int count = temp.length; + while (last < max) { + int x = temp[count - 1] + temp[count - 2]; + temp[count] = x; + count++; + last = x; + } + System.arraycopy(temp, count, temp, count - 1, max - count); + return temp; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ +// public int[] getPrimes(int max) { +// int[] temp = new int[max]; +// if (max < 2) +// return new int[0]; +// else if (max == 2) +// return new int[]{2}; +// else { +// temp[2] = 2; +// int index = 3; +// for (int i = 3; i <= max; i += 2) { +// boolean flag = true; +// for (int j = 2; j < i; j++) { +// if (i % j == 0) { +// flag = false; +// } +// } +// if (flag) { +// temp[index++] = i; +// } +// } +// if (temp[temp.length - 2] >= max) +// System.arraycopy(temp, temp.length - 1, temp, temp.length - 2, 1); +// } +// +// return temp; +// } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int[] temp = new int[max]; + int index = 0; + for (int i = 1; i <= max; i++) { + int sum = 0; + for (int j = 1; j < i; j++) { + if (i % j == 0) { + sum += j; + } + } + if (sum == i) { + temp[index++] = i; + } + } + + return temp; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @param seperator + * @return + */ + public String join(int[] array, String seperator) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + if (i == array.length - 1) { + builder.append(array[i]); + } else builder.append(array[i]).append(seperator); + } + return builder.toString(); + } + + +} diff --git a/group27/1016908591/week002/src/com/coderising/array/ArrayUtil.java b/group27/1016908591/week002/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..15b15e667c --- /dev/null +++ b/group27/1016908591/week002/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,195 @@ +package com.coderising.array; + +import java.util.Arrays; + +import javax.ws.rs.HEAD; + +import javassist.expr.NewArray; + +import com.coding.basic.*; + + +public class ArrayUtil extends ArrayList { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + int[] reArray = new int[origin.length]; + for(int i = 0;i parameters) + throws ClassNotFoundException, DocumentException, InstantiationException, IllegalAccessException, + NoSuchMethodException, InvocationTargetException{ + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + //生成set方法的数组 + View view = new View(); + String[] methodNames = createSetMethodNames(parameters); + InputStream is=Struts.class.getResourceAsStream("/struts.xml"); + //获取xml文件中的目标节点 + Element element = getTargetElement(actionName); + //得到该节点类的名称 + String className = element.attribute(1).getValue(); + //获得对应的Class对象 + Class clz = Class.forName(className); + + + + //实例化该类 + + Object obj = clz.newInstance(); + //调用这个方法,该方法是通过反射实例化(创建对象) + // 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 ("name"="test" , + //"password"="1234") , 那就应该调用 setName和setPassword方法 + + invokeObjectSetter(parameters, methodNames, clz, obj); + + + + /*根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + */ + + setViewJsp(view, element, clz, obj); + + //产生一个Map集合 + view.setParameters(createGetterMap(clz,obj)); + + return view; + + + + + + + + + + + + } + + + + private static void setViewJsp(View view, Element element, Class clz, + Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + view.setJsp(getJsp(element, executeToGetResult(clz, obj))); + + } + + //通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + private static String executeToGetResult(Class clz, Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + + + + //调用指定类中的excute的方法 + Method method = clz.getMethod("execute"); + String result = (String) method.invoke(obj); + return result; + + + + + + } + +//返回对应的Jsp + @SuppressWarnings("unchecked") + private static String getJsp(Element element, String result) { + + List elements = element.elements(); + if (elements!=null){ + for (Element e : elements) { + //如果result的值与节点的值相同则返回节点文本内容 + System.out.println(result); + if (e!=null&&result.equals(e.attribute(0).getValue())) { + return e.getTextTrim(); + } + + + + } + } + + + return null; + } + + + + + /* 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters*/ + + private static Map createGetterMap(Class clz, Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Map map = new HashMap(); + Method[] methods = clz.getMethods(); + + + + for(Method item:methods){ + if (item.getName().contains("get")) { + String key = item.getName().substring(3).toLowerCase(); + + //调用的是get方法 + Object value = item.invoke(obj); + System.out.println(item.invoke(obj)); + map.put(key,value); + + } + } + + return map; + } + + //调用set方法 + private static void invokeObjectSetter(Map parameters, + String[] methodNames, Class clz, Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + //遍历对应的方法 + for(String ke:methodNames){ + + Method method = clz.getMethod(ke,String.class); + + //调用该方法 + String key = ke.substring(3).toLowerCase(); + method.invoke(obj, parameters.get(key)); + + + + + + + + + + + } + + } + //获得根节点,返回需要的xml的节点 + private static Element getTargetElement(String actionName) { + try { + SAXReader reader = new SAXReader(); + InputStream inputStream =Struts.class.getResourceAsStream("/struts.xml"); + Document document = null; + + document = reader.read(inputStream); + Element rootNode = (Element) document.getRootElement(); + List elements = ((org.dom4j.Element) rootNode).elements(); + for (Element item : elements) { + if (actionName.equals(((org.dom4j.Element) item).attribute(0).getValue())) { + return item; + } + } + } catch (DocumentException e) { + + e.printStackTrace(); + } + return null; + } + //产生Set方法的数组 + private static String[] createSetMethodNames(Map parameters) { + String[] methodNames=new String[parameters.size()]; + int i = 0; + for (String key:parameters.keySet()){ + //产生set方法 + methodNames[i++] = "set" + key.substring(0, 1).toUpperCase() + key.substring(1); + + + } + return methodNames; + } + + +} diff --git a/group27/1016908591/week002/src/com/coderising/litestruts/StrutsTest.java b/group27/1016908591/week002/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..3b5c29cde5 --- /dev/null +++ b/group27/1016908591/week002/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,60 @@ +package com.coderising.litestruts; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + + + + + + + +import org.dom4j.DocumentException; +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, DocumentException { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view; + + view = Struts.runAction(actionName,params); + System.out.println( view.getJsp()); + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + System.out.println( view.getParameters().get("message")); + Assert.assertEquals("login successful", view.getParameters().get("message")); + + + + } + + @Test + public void testLoginActionFailed() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, DocumentException { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view; + + view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + + } +} diff --git a/group27/1016908591/week002/src/com/coderising/litestruts/View.java b/group27/1016908591/week002/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group27/1016908591/week002/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group27/1016908591/week002/src/com/coderising/litestruts/struts.xml b/group27/1016908591/week002/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/group27/1016908591/week002/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group27/1016908591/week002/src/struts.xml b/group27/1016908591/week002/src/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/group27/1016908591/week002/src/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group27/1067041567/TestColleaction/.classpath b/group27/1067041567/TestColleaction/.classpath index fb565a588d..dfa83d7793 100644 --- a/group27/1067041567/TestColleaction/.classpath +++ b/group27/1067041567/TestColleaction/.classpath @@ -2,5 +2,7 @@ + + diff --git a/group27/1067041567/TestColleaction/.settings/org.eclipse.core.resources.prefs b/group27/1067041567/TestColleaction/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000..99f26c0203 --- /dev/null +++ b/group27/1067041567/TestColleaction/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/group27/1067041567/TestColleaction/.settings/org.eclipse.jdt.core.prefs b/group27/1067041567/TestColleaction/.settings/org.eclipse.jdt.core.prefs index 7341ab1683..d17b6724d1 100644 --- a/group27/1067041567/TestColleaction/.settings/org.eclipse.jdt.core.prefs +++ b/group27/1067041567/TestColleaction/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,6 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 diff --git a/group27/1067041567/TestColleaction/RemoteSystemsTempFiles/.project b/group27/1067041567/TestColleaction/RemoteSystemsTempFiles/.project new file mode 100644 index 0000000000..5447a64fa9 --- /dev/null +++ b/group27/1067041567/TestColleaction/RemoteSystemsTempFiles/.project @@ -0,0 +1,12 @@ + + + RemoteSystemsTempFiles + + + + + + + org.eclipse.rse.ui.remoteSystemsTempNature + + diff --git a/group27/1067041567/TestColleaction/src/cn/task2/ArrayUtil.java b/group27/1067041567/TestColleaction/src/cn/task2/ArrayUtil.java new file mode 100644 index 0000000000..f3d2d7f09a --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/task2/ArrayUtil.java @@ -0,0 +1,290 @@ +package cn.task2; + +import org.junit.Test; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + enSure(origin); + int len = origin.length-1; + for(int k=0;k"+origin); + */ + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + enSure(oldArray); + int len = 0; + for(int i=0;i temp[j+1]){ + int arr = temp[j]; + temp[j] = temp[j+1]; + temp[j+1] = arr; + } + } + } + for(int i=0;i"+a); + for(int i=0;i"+a); + System.out.println(); + for(int i=0;i parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + SAXReader read = new SAXReader(); + Document document = null; + View view = new View(); + Map map = new HashMap(); + try { + document = read.read(Struts.class.getClassLoader().getResourceAsStream("struts.xml")); + //获取唯一的根节点 + Element root = document.getRootElement(); + //获取子节点的集合 + List childNode = root.elements(); + + for(Element ele : childNode){ + //获取action节点的name和class值 + String name = ele.attributeValue("name"); + String className = ele.attributeValue("class"); + + + if(name.equals(actionName)){ + try { + Class clazz = Class.forName(className); + Object obj = clazz.newInstance(); + for(Map.Entry param : parameters.entrySet()){ + String key = "set"+param.getKey().substring(0,1).toUpperCase()+param.getKey().substring(1); + Method m =clazz.getMethod(key,String.class); +// System.out.println(param.getKey()+" "+param.getValue()); + m.invoke(obj, param.getValue()); + } + + Method execute = clazz.getMethod("execute"); + Type type = execute.getReturnType(); + //获取result节点的name和返回的jsp + List list2 = ele.elements(); + for(Element e:list2){ +// System.out.println(e.attributeValue("name")); +// System.out.println(e.getText()); +// System.out.println(execute.invoke(obj)); + if(e.attributeValue("name").equals(execute.invoke(obj))){ + System.out.println(e.getText()); + view.setJsp(e.getText()); + } + } + + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + } + + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + view.setParameters(parameters); + + return view; + } +} diff --git a/group27/1067041567/TestColleaction/src/cn/task2/StrutsTest.java b/group27/1067041567/TestColleaction/src/cn/task2/StrutsTest.java new file mode 100644 index 0000000000..d7c0aacca5 --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/task2/StrutsTest.java @@ -0,0 +1,38 @@ +package cn.task2; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class StrutsTest { + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group27/1067041567/TestColleaction/src/cn/task2/View.java b/group27/1067041567/TestColleaction/src/cn/task2/View.java new file mode 100644 index 0000000000..f4fe693f43 --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/task2/View.java @@ -0,0 +1,23 @@ +package cn.task2; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group27/1067041567/TestColleaction/src/cn/test/Test.java b/group27/1067041567/TestColleaction/src/cn/test/Test.java new file mode 100644 index 0000000000..ca55b5056e --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/test/Test.java @@ -0,0 +1,11 @@ +package cn.test; + +public class Test { + + public static void main(String[] args) { + String name = "name"; + String n ="set"+name.substring(0,1).toUpperCase()+name.substring(1); + + System.out.println(n); + } +} diff --git a/group27/1067041567/TestColleaction/src/cn/test/TestReflect.java b/group27/1067041567/TestColleaction/src/cn/test/TestReflect.java new file mode 100644 index 0000000000..c05bea04de --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/test/TestReflect.java @@ -0,0 +1,39 @@ +package cn.test; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +public class TestReflect { + + public static void main(String[] args) { + + try { + Class clazz = Class.forName("cn.task2.LoginAction"); + + Method[] me = clazz.getMethods(); + + for(Method m:me){ + System.out.println(m); + } + + //Method m1 = clazz.getMethod("setName",String.class); + Object obj = clazz.newInstance(); + Method m3 = clazz.getMethod("setName",String.class); + Method mm = clazz.getMethod("getName"); + //m1.invoke(obj, "woshi"); + System.out.println(obj); + //System.out.println(m1.invoke(obj)); + m3.invoke(obj, "dassdasd-----------------"); + System.out.println(mm.invoke(obj)); + Method execute = clazz.getMethod("execute"); + Type type = execute.getReturnType(); + + System.out.println("type : "+type); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } +} diff --git a/group27/1067041567/TestColleaction/src/cn/test/TestUtil.java b/group27/1067041567/TestColleaction/src/cn/test/TestUtil.java new file mode 100644 index 0000000000..5fc93b9f6c --- /dev/null +++ b/group27/1067041567/TestColleaction/src/cn/test/TestUtil.java @@ -0,0 +1,39 @@ +package cn.test; + +import java.io.File; +import java.util.List; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import cn.task2.Struts; + +public class TestUtil { + + public static void main(String[] args) { + SAXReader read = new SAXReader(); + Document document = null; + try { + document = read.read(Struts.class.getClassLoader().getResourceAsStream("struts.xml")); + //获取唯一的根节点 + Element root = document.getRootElement(); + //获取子节点的集合 + List childNode = root.elements(); + + for(Element ele : childNode){ + System.out.println(ele.attributeValue("name")+" "+ele.attributeValue("class")); + List list2 = ele.elements(); + for(Element e:list2){ + System.out.println(e.getName()+"--"+e.attributeValue("name")+" "+e.getText()); + } + } + + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } +} diff --git a/group27/1067041567/TestColleaction/src/struts.xml b/group27/1067041567/TestColleaction/src/struts.xml new file mode 100644 index 0000000000..e4d58e912c --- /dev/null +++ b/group27/1067041567/TestColleaction/src/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group27/351592484/src/learn/ArrayList.java b/group27/351592484/src/learn/ArrayList.java new file mode 100644 index 0000000000..c0993491d1 --- /dev/null +++ b/group27/351592484/src/learn/ArrayList.java @@ -0,0 +1,93 @@ +package com.liam.learn.code2017; + +import java.lang.reflect.Array; +import java.util.Arrays; + +public class ArrayList implements List { + + private int capacity = 10; + private int size = 0; + + private Object[] elementData = null; //new Object[100]; + + public ArrayList(){ + this.capacity = capacity; + elementData = new Object[capacity]; + } + + public ArrayList(int custCapacity) { + if(custCapacity <= 0){ + throw new IllegalArgumentException("Arraylist 长度不能为负数或0"); + } + this.capacity = custCapacity; + elementData = new Object[capacity]; + } + + public void add(Object o){ + if (size >= capacity){ + enlargeCapacity(); + } + elementData[size] = o; + size++; + } + public void add(int index, Object o){ + if(index <0 || index >= size){ + throw new IllegalArgumentException("数组越界"); + } + if (size >= capacity){ + enlargeCapacity(); + } + System.arraycopy(elementData, index, elementData, index+1, size - index); + elementData[index] = o; + size++; + } + + public Object get(int index){ + if(index <0 || index >= size){ + throw new IllegalArgumentException("数组越界"); + } + return elementData[index]; + } + + public Object remove(int index){ + Object removedObj = get(index); + + int movedSize = size - (index + 1); + if (movedSize > 0) { + System.arraycopy(elementData, index+1, elementData, index, movedSize); + } + elementData[--size] = null; + + return removedObj; + } + + public int size(){ + return size; + } + + public Iterator iterator(){ + return null; + } + + + @Override + public String toString() { + if (size < capacity){ + //int needRemove = capacity - size; + Object[] toStringObj = new Object[size]; + System.arraycopy(elementData, 0, toStringObj, 0, size); + return Arrays.toString(toStringObj); + } + return Arrays.toString(elementData); + } + + private void enlargeCapacity(){ + capacity = capacity * 2; + Object[] temp = new Object[capacity]; + System.arraycopy(elementData, 0, temp, 0, size); + elementData = temp; + } + + + +} diff --git a/group27/351592484/src/learn/BinaryTreeNode.java b/group27/351592484/src/learn/BinaryTreeNode.java new file mode 100644 index 0000000000..86e8d5ce7b --- /dev/null +++ b/group27/351592484/src/learn/BinaryTreeNode.java @@ -0,0 +1,46 @@ +package com.liam.learn.code2017; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public BinaryTreeNode(Object data) { + this.data = data; + } + + public BinaryTreeNode() { + } + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + + if (left != null){ + return left = new BinaryTreeNode(o); + } + if (right !=null){ + return right = new BinaryTreeNode(o); + } + throw new RuntimeException("左右子树已经都有值了"); + } + +} diff --git a/group27/351592484/src/learn/Iterator.java b/group27/351592484/src/learn/Iterator.java new file mode 100644 index 0000000000..0f85a64dfd --- /dev/null +++ b/group27/351592484/src/learn/Iterator.java @@ -0,0 +1,7 @@ +package com.liam.learn.code2017; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group27/351592484/src/learn/LinkedList.java b/group27/351592484/src/learn/LinkedList.java new file mode 100644 index 0000000000..64c2c0e448 --- /dev/null +++ b/group27/351592484/src/learn/LinkedList.java @@ -0,0 +1,255 @@ +package com.liam.learn.code2017; + + + +public class LinkedList implements List { + private int size; + + private Node head; + + private Node tail; + + public void add(Object o){ + Node node = new Node(o, null); + if(head == null){ + head = node; + tail = node; + }else{ + tail.setNext(node); + tail = node; + } + size++; + } + public void add(int index , Object o){ + if (index < 0 || index >= size){ + throw new IllegalArgumentException("链表越界"); + } + if (index == 0){ + addFirst(o); + }else if(index == size-1){ + addLast(o); + }else{ + Node indexNode = getNode(index); + Node newNode = new Node(o, indexNode); + Node previousNode = getNode(index-1); + previousNode.setNext(newNode); + } + size++; + } + public Object get(int index){ + Node node = getNode(index); + return node.getData(); + } + + private Node getNode(int index){ + if (index < 0 || index >= size){ + throw new IllegalArgumentException("链表越界"); + } + if(index == 0){ + return head; + } + if(index == size-1){ + return tail; + } + Node temp = head; + for(int i=0; i= size){ + throw new IllegalArgumentException("链表越界"); + } + + if (index == 0){ + return removeFirst(); + }else if(index == size-1){ + return removeLast(); + }else{ + Node previousNode = getNode(index-1); + Node nextNode = getNode(index+1); + previousNode.setNext(nextNode); + size--; + } + return get(index); + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + Node node = new Node(o, null); + if(head == null){ + head = node; + tail = node; + }else{ + node.setNext(head); + head = node; + } + size++; + } + public void addLast(Object o){ + Node node = new Node(o, null); + if(head == null){ + head = node; + tail = node; + }else{ + tail.setNext(node); + tail = node; + } + size++; + } + public Object removeFirst(){ + if (head == null){ + throw new RuntimeException("链表为空"); + } + if (size ==1){ + Object ret = head.getData(); + head = null; + tail = null; + return ret; + } + Object headData = head.getData(); + head = getNode(1); + size--; + return headData; + } + public Object removeLast(){ + if (head == null){ + throw new RuntimeException("链表为空"); + } + Object tailData = tail.getData(); + tail = getNode(size-2); + size--; + return tailData; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + private Object data; + private Node next; + + public Node(Object data, Node next) { + this.data = data; + this.next = next; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Node getNext() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if(size == 0 || size ==1){ + return; + } + /*LinkedList linkedList = new LinkedList(); + for(int i=size-1; i>=0; i--){ + linkedList.add(getNode(i)); + }*/ + + Node temp = head; + head = tail; + tail = temp; + for(int i=size-2; i>=1; i--){ + getNode(i+1).setNext(getNode(i)); + } + getNode(1).setNext(tail); + } + + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + int pre = size/2; + for (int i=0; i101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public static int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/group27/351592484/src/learn/List.java b/group27/351592484/src/learn/List.java new file mode 100644 index 0000000000..9b5fc82f83 --- /dev/null +++ b/group27/351592484/src/learn/List.java @@ -0,0 +1,9 @@ +package com.liam.learn.code2017; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group27/351592484/src/learn/Queue.java b/group27/351592484/src/learn/Queue.java new file mode 100644 index 0000000000..dd6ed22559 --- /dev/null +++ b/group27/351592484/src/learn/Queue.java @@ -0,0 +1,32 @@ +package com.liam.learn.code2017; + +public class Queue { + + private LinkedList linkedList; + + public Queue() { + this.linkedList = new LinkedList(); + } + + public void enQueue(Object o){ + linkedList.add(o); + } + + public Object deQueue(){ + if (linkedList == null || isEmpty()){ + return null; + } + return linkedList.removeFirst(); + } + + public boolean isEmpty(){ + return linkedList.size()==0; + } + + public int size(){ + if (linkedList == null || isEmpty()){ + return 0; + } + return linkedList.size(); + } +} diff --git a/group13/1274639949/lesson01/src/com/hans/Stack.java b/group27/351592484/src/learn/Stack.java similarity index 50% rename from group13/1274639949/lesson01/src/com/hans/Stack.java rename to group27/351592484/src/learn/Stack.java index d370221f1a..1fc79645f1 100644 --- a/group13/1274639949/lesson01/src/com/hans/Stack.java +++ b/group27/351592484/src/learn/Stack.java @@ -1,4 +1,4 @@ -package com.hans; +package com.liam.learn.code2017; public class Stack { private ArrayList elementData = new ArrayList(); @@ -8,23 +8,16 @@ public void push(Object o){ } public Object pop(){ - if(elementData.size() <= 0){ - return null; - } - return elementData.remove(elementData.size() - 1); + return elementData.remove(elementData.size()-1); } public Object peek(){ - if(elementData.size() <= 0){ - return null; - } - return elementData.get(elementData.size() - 1); + return elementData.get(elementData.size()-1); } public boolean isEmpty(){ - return elementData.size() == 0; + return elementData.size()==0; } public int size(){ return elementData.size(); } } - diff --git a/group27/383117348/.classpath b/group27/383117348/.classpath index d98690584e..840446d6d6 100644 --- a/group27/383117348/.classpath +++ b/group27/383117348/.classpath @@ -5,5 +5,6 @@ + diff --git a/group27/383117348/.gitignore b/group27/383117348/.gitignore index 9ded3b51b7..f499c9582c 100644 --- a/group27/383117348/.gitignore +++ b/group27/383117348/.gitignore @@ -18,4 +18,5 @@ hs_err_pid* rebel.* .rebel.* -target \ No newline at end of file +target +/bin/ diff --git a/group27/383117348/src/com/coderising/array/ArrayUtil.java b/group27/383117348/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..61fd42254a --- /dev/null +++ b/group27/383117348/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,327 @@ +package com.coderising.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] 如果 a = + * [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + int[] copy = new int[origin.length]; + for (int x = 0; x < copy.length; x++) { + copy[x] = origin[x]; + } + for (int x = 0; x < origin.length; x++) { + origin[x] = copy[origin.length - 1 - x]; + System.out.println(copy[origin.length - 1 - x]); + } + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + List list = new ArrayList(); + for (int x = 0; x < oldArray.length; x++) { + if (oldArray[x] != 0) + list.add(oldArray[x]); + } + + return parseToInt(list); + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 例如 a1 = + * [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) { + int[] newArray = new int[array1.length + array2.length]; + // 如果array1为空,array2不为空,则返回array2排序后的数组 + if (array1 == null || array1.length == 0 && array2 != null && array2.length > 0) { + return sort(array2); + } + // 如果array2为空,array1不为空,则返回array1排序后的数组 + if (array1 == null || array1.length == 0 && array2 != null && array2.length > 0) { + return sort(array1); + } + // 如果都不为空,则将两个数组放入一个数组中,先排序后去重 + if (array1 != null && array2 != null & array1.length > 0 && array2.length > 0) { + // 将array1的数组正序存放 + for (int x = 0; x < array1.length; x++) { + newArray[x] = array1[x]; + } + // 将array2的数组倒序存放 + for (int x = 0; x < array2.length; x++) { + newArray[newArray.length - 1 - x] = array2[x]; + } + newArray = sort(newArray); + newArray = getDistinct(newArray); + } + return newArray; + } + + // 数组去重 + private int[] getDistinct(int[] newArray) { + List list = new java.util.ArrayList(); + for (int i = 0; i < newArray.length; i++) { + if (!list.contains(newArray[i])) {// 如果list数组不包括num[i]中的值的话,就返回true。 + list.add(newArray[i]); // 在list数组中加入num[i]的值。已经过滤过。 + } + } + int[] result = parseToInt(list); + return result; + } + + // 冒泡排序 + private int[] sort(int[] array1) { + // TODO Auto-generated method stub + int[] arr = array1; + for (int i = 0; i < arr.length; i++) + for (int j = 0; j < arr.length - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + int t = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = t; + } + } + return arr; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + int[] newArray = new int[oldArray.length + size]; + for (int x = 0; x < oldArray.length; x++) { + newArray[x] = oldArray[x]; + } + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 例如, max = 15 , + * 则返回的数组应该为 [1,1,2,3,5,8,13] max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + int n = 0; + for (int i = 1, j = 1, k; i < max; n++) { + k = i + j; + i = j; + j = k; + } + int[] newArray = new int[n]; + if (n > 1) { + newArray[0] = 1; + newArray[1] = 1; + } + for (int i = 2; i < n; i++) { + newArray[i] = newArray[i - 1] + newArray[i - 2]; + } + return newArray; + } + + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + int n = 0; + for (int i = 2; i < max; i++) { + if (primeNumber(i)) + n++; + } + + int[] newArray = new int[n]; + for (int i = 2, j = 0; i < max; i++) { + if (primeNumber(i)) { + newArray[j++] = i; + } + } + return newArray; + } + + private boolean primeNumber(int number) { + for (int i = 2; i < number; i++) { + if (number % i == 0) + return false; + } + return true; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + List list = new ArrayList(); + for (int i = 2; i < max; i++) { + int sum = 0; + // 查找因数 + for (int j = 1; j < i; j++) { + if (i % j == 0) { + sum += j; + } + } + if (sum == i) + list.add(i); + + } + + return parseToInt(list); + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) { + String str = ""; + if (array.length > 0) { + for (int i = 0; i < array.length; i++) { + str += array[i] + seperator; + } + str = str.substring(0, str.length() - seperator.length()); + } + return str; + } + + /** + * 将集合转化为int数组 + * + * @param list + * @return + */ + private int[] parseToInt(List list) { + int[] arr = new int[list.size()]; + for (int x = 0; x < list.size(); x++) { + arr[x] = list.get(x); + } + return arr; + } + + /*********************************** 单元测试 ***********************************/ + @Test + public void testReserve() { + int[] arr = { 7, 9, 30, 3 }; + reverseArray(arr); + for (int x = 0; x < 4; x++) { + System.out.println(arr[x]); + } + } + + @Test + public void testZero() { + int oldArr[] = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 }; + int[] arr = removeZero(oldArr); + for (int x = 0; x < arr.length; x++) { + System.out.print(arr[x] + " "); + } + } + + @Test + public void testMerge() { + // a1=[3, 5, 7,8] a2 = [4, 5, 6,7] + int[] a1 = { 3, 5, 7, 8 }; + int[] a2 = { 4, 5, 6, 7 }; + // a3 = [3,4,5,6,7,8] + int[] a3 = merge(a1, a2); + for (int x = 0; x < a3.length; x++) { + System.out.print(a3[x] + " "); + } + } + + @Test + public void testGrow() { + int[] oldArray = { 2, 3, 6 }; + int[] newArray = grow(oldArray, 3); + for (int x = 0; x < newArray.length; x++) { + System.out.println(newArray[x]); + } + } + + @Test + public void testFibo() { + // 1,1,2,3,5,8,13 + int[] arr = fibonacci(20); + for (int x = 0; x < arr.length; x++) { + System.out.print(arr[x] + " "); + } + } + + @Test + public void testPrime() { + int arr[] = getPrimes(23); + for (int x = 0; x < arr.length; x++) { + System.out.print(arr[x]); + System.out.print(" "); + } + } + + @Test + public void testPerfectNum() { + int[] arr = getPerfectNumbers(25); + for (int x = 0; x < arr.length; x++) { + System.out.println(arr[x]); + } + + } + + @Test + public void testJoin() { + int[] arr = new int[10]; + for (int x = 0; x < arr.length; x++) { + arr[x] = x; + } + String s = join(arr, "--"); + System.out.println(s); + } + + @Test + public void testParseToInt() { + List list = new ArrayList(); + for (int x = 0; x < 10; x++) { + list.add(x); + } + int[] arr = parseToInt(list); + for (int x = 0; x < arr.length; x++) { + System.out.println(arr[x]); + } + } + +} diff --git a/group27/383117348/src/com/coderising/litestruts/LoginAction.java b/group27/383117348/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..1005f35a29 --- /dev/null +++ b/group27/383117348/src/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group27/383117348/src/com/coderising/litestruts/Struts.java b/group27/383117348/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..0619f1a88e --- /dev/null +++ b/group27/383117348/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,121 @@ +package com.coderising.litestruts; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +@SuppressWarnings("unchecked") +public class Struts { + private static List list = new ArrayList(); + static{ + SAXReader read = new SAXReader(); + Document doc = null; + try { + doc = read.read(Struts.class.getResourceAsStream("struts.xml")); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Element root = doc.getRootElement(); + list = root.elements(); + } + + + + public static View runAction(String actionName, Map parameters){ + String className = ""; + Map viewName = new HashMap(); + Element element = null; + View view = new View(); + for(Element e : list){ + if(e.attributeValue("name").equals(actionName)){ + className = e.attribute("class").getText(); + element = e; + } + } + Iterator e = element.elementIterator(); + while(e.hasNext()){ + Element result = e.next(); + if(result.getName().equals("result")); + viewName.put(result.attributeValue("name"), result.getStringValue()); + } + Class clazz = null; + try { + clazz = Class.forName(className); + Object obj = clazz.newInstance(); + Iterator keys = parameters.keySet().iterator(); + while(keys.hasNext()){ + String key = keys.next(); + String methodName = "set"+key.substring(0,1).toUpperCase()+key.substring(1).toLowerCase(); + Method method =obj.getClass().getMethod(methodName, String.class); + method.invoke(obj, parameters.get(key)); + } + Method execute = obj.getClass().getDeclaredMethod("execute"); + String result = (String)execute.invoke(obj); + Map map = new HashMap(); + Method[] methods = obj.getClass().getDeclaredMethods(); + for(Method method : methods){ + String methodName = method.getName(); + if(methodName.startsWith("get")){ + map.put(methodName.substring(3,4).toLowerCase()+methodName.substring(4), method.invoke(obj)); + String s = (String)method.invoke(obj); + System.out.println(methodName.substring(3,4).toLowerCase()+methodName.substring(4)); + System.out.println(s); + } + + } + view.setJsp(viewName.get(result)); + view.setParameters(map); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return view; + } + + public static void main(String[] args) { + SAXReader read = new SAXReader(); + Document doc = null; + try { + doc = read.read(Struts.class.getResourceAsStream("struts.xml")); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Element root = doc.getRootElement(); + list = root.elements(); + for(Element e : list){ + System.out.println(e.attributeValue("class")); + } + } +} diff --git a/group27/383117348/src/com/coderising/litestruts/StrutsTest.java b/group27/383117348/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..a44c1878ac --- /dev/null +++ b/group27/383117348/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group27/383117348/src/com/coderising/litestruts/View.java b/group27/383117348/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..0194c681f6 --- /dev/null +++ b/group27/383117348/src/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group27/383117348/src/com/coderising/litestruts/struts.xml b/group27/383117348/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..0582b7d4ea --- /dev/null +++ b/group27/383117348/src/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group27/513274874/homework/src/com/coding/basic/ArrayList.java b/group27/513274874/homework/src/com/coding/basic/ArrayList.java index 1b6f5c4e7d..9e55e92529 100644 --- a/group27/513274874/homework/src/com/coding/basic/ArrayList.java +++ b/group27/513274874/homework/src/com/coding/basic/ArrayList.java @@ -65,16 +65,20 @@ public Object get(int index) { public Object remove(int index) { Object o = this.get(index); - this.size--; + //index后面的数向前移动一位 for (int cur = index + 1; cur < this.size; cur++) { this.elementData[cur] = this.elementData[cur + 1]; } + //最后一个元素删除 + this.elementData[this.size-1] = null; + + this.size--; return o; } public int size() { - return this.size; + return this.size + 1; } public Iterator iterator() { diff --git a/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtil.java b/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..1684b512ad --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtil.java @@ -0,0 +1,262 @@ +package com.coding.coderising.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + * 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + * 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public static void reverseArray(final int[] origin) { + int size = origin.length; + if (size <= 0) return; + + int[] newArray = copyOf(origin); + + for (int i = 0; i < size; i++) { + origin[i] = newArray[size - 1 - i]; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public static int[] removeZero(int[] oldArray) { + int size = oldArray.length; + int countZero = 0; + //首先判断数组中0的个数 + for (int i : oldArray) { + if (i == 0) countZero++; + } + int[] newArray = new int[size - countZero]; + //cur 命名newArray的游标 + int cur = 0; + for (int i = 0; i < size; i++) { + if (oldArray[i] == 0) continue; + newArray[cur++] = oldArray[i]; + } + + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public static int[] merge(int[] array1, int[] array2) { + //判断数组是否为空 + int size1 = array1.length; + int size2 = array2.length; + if (size1 <= 0 || size2 <= 0) + return size1 <= 0 ? array2 : array1; + + //先将两个数组合并成一个数组 + int[] newArray = new int[size1 + size2]; + System.arraycopy(array1, 0, newArray, 0, size1); + System.arraycopy(array2, 0, newArray, size1, size2); + + + //对数组进行插入排序(假定array1已经是有序数组) + int in, out; + for (out = size1; out < newArray.length; out++) { + in = out; + int temp = newArray[out]; + + while (in > 0 && newArray[in - 1] >= temp) { + //右移 + newArray[in] = newArray[in - 1]; + --in; + } + newArray[in] = temp; + } + return newArray; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public static int[] grow(int[] oldArray, int size) { + int oldSize = oldArray.length; + if (oldSize == 0) return new int[size]; + + if (size <= 0) return oldArray; + + int[] newArray = new int[oldSize + size]; + System.arraycopy(oldArray, 0, newArray, 0, oldSize); + + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public static int[] fibonacci(int max) { + //先确定数组长度 + if (max == 1) return new int[]{}; + //这里的cur指的是数组的下标,从0开始,而不是数学函数1开始 + int cur = 2; + int val_1 = 1; + int val_2 = 1; + while (val_1 + val_2 <= max) { + int temp = val_1; + val_1 = val_2; + val_2 += temp; + ++cur; + } + + int[] newArray = new int[cur]; + for (int i = 0; i < cur; i++) { + if (i == 0 || i == 1) { + newArray[i] = 1; + continue; + } + newArray[i] = newArray[i - 1] + newArray[i - 2]; + + } + return newArray; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public static int[] getPrimes(int max) { + //先确定数组长度 + //判断质数循环 + int count = 0; + for (int i = 1; i < max; i++) { + //去掉偶数 + if (i == 1 || (i % 2 == 0 && i != 2)) continue; + boolean flag = true; + for (int j = 3; j <= Math.sqrt(i); j += 2) { + if (i % j == 0) { + flag = false; + break; + } + } + if (flag) count++; + } + int[] newArray = new int[count]; + int cur = 0; + for (int i = 1; i < max; i++) { + //去掉偶数 + if (i == 1 || (i % 2 == 0 && i != 2)) continue; + //判断到开根号即可 + boolean flag = true; + for (int j = 3; j <= Math.sqrt(i); j += 2) { + if (i % j == 0) { + flag = false; + + } + } + if (flag) { + newArray[cur] = i; + ++cur; + } + + } + + + return newArray; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public static int[] getPerfectNumbers(int max) { + //求数组长度 + int count = 0; + for (int a = 1; a <= max; a++) { + int sum = 0; + for (int i = 1; i <= a / 2; i++) + if (a % i == 0) + sum += i; + if (a == sum) + ++count; + } + + int[] newArray = new int[count]; + int cur = 0; + for (int a = 1; a <= max; a++) { + int sum = 0; + for (int i = 1; i <= a / 2; i++) + if (a % i == 0) + sum += i; + if (a == sum) { + newArray[cur] = a; + ++cur; + } + } + + return newArray; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @param seperator + * @return + */ + public static String join(int[] array, String seperator) { + int size = array.length; + if (size == 0) return ""; + StringBuffer sb = new StringBuffer(""); + for (int i = 0; i < size - 1; i++) { + sb.append(array[i]).append(seperator); + } + sb.append(array[size - 1]); + return sb.toString(); + } + + + /** + * 类私有函数,复制返回一个新的数组 + */ + private static int[] copyOf(int[] source) { + int size = source.length; + if (size <= 0) return null; + + int[] newArray = new int[size]; + //int[] ints = Arrays.copyOf(origin, size); + System.arraycopy(source, 0, newArray, 0, size); + return newArray; + } + + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtilTest.java b/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtilTest.java new file mode 100644 index 0000000000..7f5ca8fdf6 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/array/ArrayUtilTest.java @@ -0,0 +1,110 @@ +package com.coding.coderising.array; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * ArrayUtil Tester. + * + * @author + * @version 1.0 + * @since
三月 14, 2017
+ */ +public class ArrayUtilTest { + + int[] testArray ; + + @Before + public void before() throws Exception { + } + + @After + public void after() throws Exception { + testArray = new int[]{}; + } + + /** + * Method: reverseArray(final int[] origin) + */ + @Test + public void testReverseArray() throws Exception { + testArray = new int[]{1,3,5,7,9,4,6}; + ArrayUtil.reverseArray(testArray); + Assert.assertArrayEquals(new int[]{6,4,9,7,5,3,1},testArray); + } + + + /** + * Method: removeZero(int[] oldArray) + */ + @Test + public void testRemoveZero() throws Exception { + testArray = new int[]{1,3,0,7,0,4,6}; + int[] newArray = ArrayUtil.removeZero(testArray); + Assert.assertArrayEquals(new int[]{1,3,7,4,6}, newArray); + } + + /** + * Method: merge(int[] array1, int[] array2) + */ + @Test + public void testMerge() throws Exception { + int[] testArray1 = new int[]{1,3,6,8,9}; + int[] testArray2 = new int[]{2,3,3,10,12}; + + int[] mergedArray = ArrayUtil.merge(testArray1,testArray2); + Assert.assertArrayEquals(new int[]{1,2,3,3,3,6,8,9,10,12},mergedArray); + } + + /** + * Method: grow(int[] oldArray, int size) + */ + @Test + public void testGrow() throws Exception { + testArray = new int[]{1,2,3,4,5,6}; + int[] grewArray = ArrayUtil.grow(testArray,4); + Assert.assertArrayEquals(new int[]{1,2,3,4,5,6,0,0,0,0},grewArray); + + } + + /** + * Method: fibonacci(int max) + */ + @Test + public void testFibonacci() throws Exception { + int[] fibArray = ArrayUtil.fibonacci(20); + Assert.assertArrayEquals(new int[]{1,1,2,3,5,8,13},fibArray); + } + + /** + * Method: getPrimes(int max) + */ + @Test + public void testGetPrimes() throws Exception { + testArray = ArrayUtil.getPrimes(23); + Assert.assertArrayEquals(new int[]{2,3,5,7,11,13,17,19},testArray); + } + + /** + * Method: getPerfectNumbers(int max) + */ + @Test + public void testGetPerfectNumbers() throws Exception { + testArray = ArrayUtil.getPerfectNumbers(1000); + Assert.assertArrayEquals(new int[]{6,28,496},testArray); + } + + /** + * Method: join(int[] array, String seperator) + */ + @Test + public void testJoin() throws Exception { + testArray = new int[]{1,2,3,5,7,9,12}; + String seperated = ArrayUtil.join(testArray,"-"); + Assert.assertEquals("1-2-3-5-7-9-12",seperated); + } + + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/DownloadThread.java b/group27/513274874/homework/src/com/coding/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..1456314140 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/FileDownloader.java b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..f5d7999eb4 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/FileDownloaderTest.java b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..8171ee5763 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/api/Connection.java b/group27/513274874/homework/src/com/coding/coderising/download/api/Connection.java new file mode 100644 index 0000000000..9710e270e1 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionException.java b/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..8dbfe95dda --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionManager.java b/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..fb44ede457 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/api/DownloadListener.java b/group27/513274874/homework/src/com/coding/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..4cd0b3eab1 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionImpl.java b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..32f03efdc7 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionManagerImpl.java b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..046f7c49a4 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/group27/513274874/homework/src/com/coding/coderising/litestruts/LoginAction.java b/group27/513274874/homework/src/com/coding/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..689678f3ad --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coding.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group27/513274874/homework/src/com/coding/coderising/litestruts/Struts.java b/group27/513274874/homework/src/com/coding/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..7aa7dacb4a --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/litestruts/Struts.java @@ -0,0 +1,254 @@ +package com.coding.coderising.litestruts; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.io.File; +import java.io.FileNotFoundException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + + +public class Struts { + + private static Struts instance = null; + private static Map strutsXml; + + private Struts() { + } + + /** + * 单例模式初始化struts.xml,而不是每次跑runAction的时候都要初始化一次 + * + * @return + */ + public static Struts init() throws FileNotFoundException { + + if (instance == null) { + /** + * 0. 读取配置文件struts.xml + */ + //创建SAXReader对象 + SAXReader reader = new SAXReader(); + //读取文件 转换成Document + Document document = null; + try { + document = reader.read(new File("src/com/coding/coderising/litestruts/struts.xml")); + } catch (DocumentException e) { + e.printStackTrace(); + } + //获取根节点元素对象 + Element root = document.getRootElement(); + if ("struts".equals(root.getName())) { + strutsXml = new HashMap(); + + Iterator actions = root.elementIterator(); + while (actions.hasNext()) { + Element action = actions.next(); + List attrList = action.attributes(); + + String actionName = null; + StrutsXml xml = null; + if (!"action".equals(action.getName())) { + continue; + } + //遍历属性节点 + for (Attribute attribute : attrList) { + xml = new StrutsXml(); + if ("name".equals(attribute.getName())) { + actionName = attribute.getValue(); + } + if ("class".equals(attribute.getName())) { + xml.setClazz(attribute.getValue()); + //获取result信息 + Iterator results = action.elementIterator(); + while (results.hasNext()) { + Element result = results.next(); + List resultList = result.attributes(); + for (Attribute resultAttr : resultList) { + //System.out.println(resultAttr.getValue() + " ,"+result.getText()); + xml.getResult().put(resultAttr.getValue(), result.getText()); + } + } + + } + //System.out.println("属性"+attribute.getName() +":" + attribute.getValue()); + } + + strutsXml.put(actionName, xml); + } + } else { + throw new FileNotFoundException("not a struts XML file !"); + } + + + instance = new Struts(); + } + return instance; + } + + public static View runAction(String actionName, Map parameters) { + + if (instance == null) return null; + if (actionName == null || "".equals(actionName.trim())) return null; + View view = new View(); + StrutsXml struts = strutsXml.get(actionName); + + Class clazz = null; + /** + * 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + * 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + * ("name"="test" , "password"="1234") ,那就应该调用 setName和setPassword方法 + */ + //获取相应处理的action + if (struts != null) { + String className = struts.getClazz(); + try { + clazz = Class.forName(className); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } else { + throw new NullPointerException("action not found in struts file !"); + } + + if (clazz != null) { + Object action = null; + try { + action = clazz.newInstance(); + + //反射调用设置参数 + for (Map.Entry entry : parameters.entrySet()) { + String para = entry.getKey(); + if (!checkField(clazz, para)) continue; + //根据习惯,类的属性首字母在调用时大写,例如属性名是 age,则类方法为getAge + PropertyDescriptor pd = new PropertyDescriptor(para, clazz); + + Method setMethod = pd.getWriteMethod();//获得set方法 + + setMethod.invoke(action, entry.getValue()); + + } + /** + * 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + */ + //执行execute() + Method excuteMethod = clazz.getDeclaredMethod("execute"); + String result = (String) excuteMethod.invoke(action); + //通过xml文件获取返回值 + String jsp = struts.getResult().get(result); + + if (jsp == null || jsp.trim().equals("")) { + throw new NullPointerException("the requested file is not found !"); + } + /** + * 3. 通过反射找到对象的所有getter方法(例如 getMessage), + * 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + * 放到View对象的parameters + */ + //执行get方法 + Map viewMap = new HashMap<>(); + Field[] fields = clazz.getDeclaredFields();//获得属性 + + for (Field field : fields) { + String getMethodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1); + Method getMethod = clazz.getDeclaredMethod(getMethodName); + String returnVal = (String) getMethod.invoke(action); + viewMap.put(field.getName(), returnVal); + } + /** + * 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + * 放到View对象的jsp字段中。 + */ + view.setJsp(jsp); + view.setParameters(viewMap); + + } catch (IntrospectionException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } + } + + return view; + + + } + + private static boolean checkField(Class clazz, String fieldName) { + if (fieldName == null || fieldName.trim().equals("")) return false; + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (fieldName.equals(field.getName())) return true; + } + return false; + } + + + public static void main(String args[]) { + try { + Struts.init(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + Map paras = new HashMap<>(); + paras.put("name", "test"); + paras.put("password", "1234"); + View view = Struts.runAction("login", paras); + } +} + +class StrutsXml { + private String actionName; + private String clazz; + private Map result = new HashMap<>(); + + public StrutsXml(String actionName, String clazz, Map result) { + this.actionName = actionName; + this.clazz = clazz; + this.result = result; + } + + public StrutsXml() { + } + + public String getActionName() { + return actionName; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public String getClazz() { + return clazz; + } + + public void setClazz(String clazz) { + this.clazz = clazz; + } + + public Map getResult() { + return result; + } + + public void setResult(Map result) { + this.result = result; + } +} \ No newline at end of file diff --git a/group27/513274874/homework/src/com/coding/coderising/litestruts/StrutsTest.java b/group27/513274874/homework/src/com/coding/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..9d876abfa4 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/litestruts/StrutsTest.java @@ -0,0 +1,53 @@ +package com.coding.coderising.litestruts; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + + + + + +public class StrutsTest { + @Before + public void before() throws Exception { + Struts.init(); + } + + @After + public void after() throws Exception { + } + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group27/513274874/homework/src/com/coding/coderising/litestruts/View.java b/group27/513274874/homework/src/com/coding/coderising/litestruts/View.java new file mode 100644 index 0000000000..ab1297a4a0 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coding.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group27/513274874/homework/src/com/coding/coderising/litestruts/struts.xml b/group27/513274874/homework/src/com/coding/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..92cb2bcb23 --- /dev/null +++ b/group27/513274874/homework/src/com/coding/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group27/514302761/src/com/company/code/ArrayList.java b/group27/514302761/src/com/company/code/ArrayList.java new file mode 100644 index 0000000000..9441f256bb --- /dev/null +++ b/group27/514302761/src/com/company/code/ArrayList.java @@ -0,0 +1,75 @@ +package com.company.code; + +import java.util.Arrays; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + if(size+1>elementData.length){ + elementData= Arrays.copyOf(elementData,elementData.length/3*2); + } + elementData[size++]=o; + } + public void add(int index, Object o){ + if(index<0||index>size){ + throw new IndexOutOfBoundsException(); + } + if(size+1>elementData.length){ + elementData=Arrays.copyOf(elementData,elementData.length/3*2); + } + System.arraycopy(elementData,index,elementData,index+1,size-index); + elementData[index]=o; + size++; + } + + + public Object get(int index){ + if(index<0||index>=size){ + throw new IndexOutOfBoundsException(); + } + return elementData[index]; + } + + public Object remove(int index){ + Object old=elementData[index]; + System.arraycopy(elementData,index+1,elementData,index,size-1-index); + size--; + return old; + } + + public int size(){ + for(int i=0;i0){ + if(null==compareNode.getLeft()){ + compareNode.setLeft(insercode); + break; + } + compareNode=compareNode.getLeft(); + }else if(result<0){ + if(null==compareNode.getRight()){ + compareNode.setRight(insercode); + break; + } + compareNode=compareNode.getLeft(); + } + } + } + return insercode; + } + +} diff --git a/group27/514302761/src/com/company/code/Iterator.java b/group27/514302761/src/com/company/code/Iterator.java new file mode 100644 index 0000000000..b9ee6d2501 --- /dev/null +++ b/group27/514302761/src/com/company/code/Iterator.java @@ -0,0 +1,7 @@ +package com.company.code; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group27/514302761/src/com/company/code/LinkedList.java b/group27/514302761/src/com/company/code/LinkedList.java new file mode 100644 index 0000000000..8131fffbd4 --- /dev/null +++ b/group27/514302761/src/com/company/code/LinkedList.java @@ -0,0 +1,249 @@ +package com.company.code; + + +import java.util.NoSuchElementException; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + if(null==head){ + head=new Node(); + head.data=o; + }else { + Node node=head; + while (null!=node.next){ + node=node.next; + } + Node addNode=new Node(); + addNode.data=o; + node.next=addNode; + } + } + public void add(int index , Object o){ + int size=size(); + if(index<0&&index>size){ + throw new IndexOutOfBoundsException(); + } + if(index==size){ + add(o); + return; + } + if (size==0){ + head=new Node(); + head.data=o; + return; + } + Node node=head; + Node addNode=new Node(); + addNode.data=o; + for (int i=0;isize()-1){ + throw new IndexOutOfBoundsException(); + } + Node node=head; + for (int i=0;isize()-1){ + throw new IndexOutOfBoundsException(); + } + Node removeNode=head; + if (index==0){ + head=head.next; + }else { + Node node=head; + for (int i=0;i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和list均包含已升序排列的整数 + * 从当前链表中取出那些list所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public static int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/group27/514302761/src/com/company/code/List.java b/group27/514302761/src/com/company/code/List.java new file mode 100644 index 0000000000..d142c6e2bf --- /dev/null +++ b/group27/514302761/src/com/company/code/List.java @@ -0,0 +1,9 @@ +package com.company.code; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/group27/514302761/src/com/company/code/Queue.java b/group27/514302761/src/com/company/code/Queue.java new file mode 100644 index 0000000000..6d4eec7573 --- /dev/null +++ b/group27/514302761/src/com/company/code/Queue.java @@ -0,0 +1,21 @@ +package com.company.code; + +public class Queue { + private LinkedList elementDatas=new LinkedList(); + public void enQueue(Object o){ + elementDatas.add(o); + } + + public Object deQueue(){ + + return elementDatas.removeFirst(); + } + + public boolean isEmpty(){ + return size()==0; + } + + public int size(){ + return elementDatas.size(); + } +} diff --git a/group27/514302761/src/com/company/code/Stack.java b/group27/514302761/src/com/company/code/Stack.java new file mode 100644 index 0000000000..e4c745c0a7 --- /dev/null +++ b/group27/514302761/src/com/company/code/Stack.java @@ -0,0 +1,32 @@ +package com.company.code; + +import java.util.EmptyStackException; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop() + { + if(isEmpty()){ + throw new EmptyStackException(); + } + return elementData.get(size()-1); + } + + public Object peek(){ + if(isEmpty()){ + throw new EmptyStackException(); + } + return elementData.get(size()-1); + } + public boolean isEmpty(){ + return size()==0; + } + public int size(){ + return elementData.size(); + } +} diff --git a/group27/514302761/src/com/company/coderising/array/ArrayUtil.java b/group27/514302761/src/com/company/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..9531bb9853 --- /dev/null +++ b/group27/514302761/src/com/company/coderising/array/ArrayUtil.java @@ -0,0 +1,211 @@ +package com.company.coderising.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + * 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + * 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + int n = origin.length; + for (int i = 0; i < n / 2; i++) { + int temp = origin[i]; + origin[i] = origin[n - 1 - i]; + origin[n - 1 - i] = temp; + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + if (oldArray.length == 0) { + return null; + } + int count = 0; + for (int i = 0; i < oldArray.length - 1; i++) { + if (oldArray[i] == 0) { + count++; + } + } + int[] newArray = new int[oldArray.length - count]; + int j = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + newArray[j++] = oldArray[i]; + } + } + return newArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) { + ArrayList arrayList = new ArrayList(); + for (int i = 0; i < array1.length; i++) { + if (!arrayList.contains(array1[i])) { + arrayList.add(array1[i]); + } + } + for (int i = 0; i < array2.length; i++) { + if (!arrayList.contains(array2[i])) { + arrayList.add(array2[i]); + } + } + int[] newArray = new int[arrayList.size()]; + for (int i = 0; i < arrayList.size(); i++) { + newArray[i] = arrayList.get(i); + } + Arrays.sort(newArray); + return newArray; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + int[] newArray = new int[oldArray.length + size]; + for (int i = 0; i < oldArray.length; i++) { + newArray[i] = oldArray[i]; + } + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + if (max == 1) { + return new int[]{}; + } else if (max == 2) { + return new int[]{1, 1}; + } else { + List list = new ArrayList(); + list.add(1); + list.add(1); + int pos = 2; + while (pos < max) { + list.add(pos); + pos = list.get(list.size() - 1) + list.get(list.size() - 2); + } + int[] newArray = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + newArray[i] = list.get(i); + } + return newArray; + } + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + if (max <= 2) { + return null; + } + List list = new ArrayList(); + list.add(2); + for (int i = 3; i < max; i++) { + int j = 2; + for (; j < Math.sqrt(i); j++) { + if (i % j == 0) { + break; + } + } + if (i % j != 0) { + list.add(i); + } + } + int[] newArray = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + newArray[i] = list.get(i); + } + return newArray; + + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + + List list = new ArrayList(); + for (int j = 2; j < max; j++) { + int val = 0; + for (int i = 1; i < j; i++) { + if (j % i == 0) { + val = val + i; + } + if (val == j) { + list.add(j); + } + } + if (list.size() != 0) { + int[] newArray = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + newArray[i] = list.get(i); + } + return newArray; + } + } + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @param + * @return + */ + public String join(int[] array, String seperator) { + String str = "" + array[0]; + for (int i = 1; i < array.length; i++) { + str = str + seperator + array[i]; + } + return str; + } +} diff --git a/group27/514302761/src/com/company/coderising/litestruts/LoginAction.java b/group27/514302761/src/com/company/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..7d557f2c9a --- /dev/null +++ b/group27/514302761/src/com/company/coderising/litestruts/LoginAction.java @@ -0,0 +1,36 @@ +package com.company.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + public String getPassword() { + return password; + } + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/group27/514302761/src/com/company/coderising/litestruts/Struts.java b/group27/514302761/src/com/company/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..32079985ae --- /dev/null +++ b/group27/514302761/src/com/company/coderising/litestruts/Struts.java @@ -0,0 +1,81 @@ +package com.company.coderising.litestruts; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + try { + DocumentBuilderFactory dbfactory=DocumentBuilderFactory.newInstance(); + DocumentBuilder dbuilder=dbfactory.newDocumentBuilder(); + Document doc=dbuilder.parse("src/com/company/litestruts/struts.xml"); + doc.getDocumentElement().normalize(); + + NodeList list=doc.getElementsByTagName("action"); + for(int i=0;i map=new HashMap(); + map.put("message",getMessage.invoke(o).toString()); + View view=new View(); + view.setParameters(map); + NodeList nodeListT=element.getElementsByTagName("result"); + for (int j=0;j params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group27/514302761/src/com/company/coderising/litestruts/View.java b/group27/514302761/src/com/company/coderising/litestruts/View.java new file mode 100644 index 0000000000..867eb0408d --- /dev/null +++ b/group27/514302761/src/com/company/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.company.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/group27/514302761/src/com/company/coderising/litestruts/struts.xml b/group27/514302761/src/com/company/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..171848ecd1 --- /dev/null +++ b/group27/514302761/src/com/company/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group27/514402862/dataStructure/pom.xml b/group27/514402862/dataStructure/pom.xml new file mode 100644 index 0000000000..f870b75fce --- /dev/null +++ b/group27/514402862/dataStructure/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + com.zzl + dataStructure + 0.0.1-SNAPSHOT + + + + junit + junit + 4.11 + + + \ No newline at end of file diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/ArrayList.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/ArrayList.java new file mode 100644 index 0000000000..f95f3a4d35 --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/ArrayList.java @@ -0,0 +1,91 @@ +package com.zzl.util; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +public class ArrayList implements List{ + + private static final int DEFAULT_SIZE = 4; + + private int size = 0; + private Object[] elementData = new Object[DEFAULT_SIZE]; + + public void add(Object o){ + ensureCapacity(size + 1); + elementData[size++] = o; + } + + public void add(int index, Object o){ + rangeCheck(index); + + ensureCapacity(size + 1); + System.arraycopy(elementData, index, elementData, index+1, size - index); + elementData[index] = o; + size++; + } + + public Object get(int index){ + rangeCheck(index); + + return elementData[index]; + } + + public Object remove(int index){ + rangeCheck(index); + + Object oldValue = elementData[index]; + + int moveNum = size - index - 1; + if(moveNum > 0) + System.arraycopy(elementData, index+1, elementData, index, moveNum); + + elementData[--size] = null; + return oldValue; + } + + public int size(){ + return size; + } + + public Iterator iterator(){ + return new ArrayListIterator(); + } + + private void rangeCheck(int index){ + if(index > size || index < 0) + throw new IndexOutOfBoundsException("Index:" + index + "size:" + size); + } + + private void ensureCapacity(int minCapacity){ + if(minCapacity <= DEFAULT_SIZE){ + minCapacity = DEFAULT_SIZE; + } + + if(minCapacity - elementData.length > 0) + grow(minCapacity); + } + + private void grow(int minCapacity){ + int oldSize = elementData.length; + int newSize = oldSize + DEFAULT_SIZE; + elementData = Arrays.copyOf(elementData, newSize); + } + + private class ArrayListIterator implements Iterator{ + int cursor; + + @Override + public boolean hasNext() { + return cursor < size; + } + + @Override + public Object next() { + if (hasNext()){ + return elementData[cursor++]; + } + throw new NoSuchElementException(); + } + + } +} diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java new file mode 100644 index 0000000000..37fd8a3d4f --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java @@ -0,0 +1,34 @@ +package com.zzl.util; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private int size = 0; + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + data = o; + + return this; + } +} diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/Iterator.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Iterator.java new file mode 100644 index 0000000000..33dba5b016 --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Iterator.java @@ -0,0 +1,6 @@ +package com.zzl.util; + +public interface Iterator { + public boolean hasNext(); + public Object next(); +} diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/LinkedList.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/LinkedList.java new file mode 100644 index 0000000000..3ddeb2fb25 --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/LinkedList.java @@ -0,0 +1,159 @@ +package com.zzl.util; + +import java.util.NoSuchElementException; + +public class LinkedList implements List{ + + private int size = 0; + private Node head; + private Node last; + + void linkFirst(Object o){ + final Node h = head; + final Node newNode = new Node(o, h); + head = newNode; + if(h == null) + last = newNode; + + size++; + } + + void linkLast(Object o){ + final Node l = last; + final Node newNode = new Node(o, null); + last = newNode; + if(l == null) + head = newNode; + else + l.next = newNode; + + size++; + } + + void linkBefore(Object o, Node succ){ + final Node next = succ.next; + final Node newNode = new Node(o, next); + succ.next = newNode; + size++; + } + + @Override + public void add(Object o) { + linkLast(o); + } + + @Override + public void add(int index, Object o) { + rangeCheck(index); + + if(index == 0) + linkFirst(o); + else if(index == size) + linkLast(o); + else + linkBefore(o, node(index - 1)); + } + + @Override + public Object get(int index) { + rangeCheck(index); + + return node(index).data; + } + + @Override + public Object remove(int index) { + rangeCheck(index); + + return changeNode(node(index), index); + } + + @Override + public int size() { + return size; + } + + public void addFirst(Object o){ + linkFirst(o); + } + + public Object removeFirst(){ + return remove(0); + } + + public Object removeLast(){ + return remove(size - 1); + } + + public Iterator iterator(){ + return new LinkedListIterator(); + } + + private Object changeNode(Node oldNode, int index){ + Object oldNodeValue = oldNode.data; + if(index == 0){ + head = oldNode.next; + }else { + Node oldNodePrev = node(index - 1); + oldNodePrev.next = oldNode.next; + if(null == oldNode.next){ + last = oldNodePrev; + } + } + oldNode.data = null; + oldNode.next = null; + + size--; + return oldNodeValue; + } + + private void rangeCheck(int index){ + if(index > size || index < 0) + throw new IndexOutOfBoundsException("Index:" + index + "size:" + size); + } + + Node node(int index){ + Node x = head; + for(int i = 0; i < index; i++) + x = x.next; + return x; + } + + private static class Node{ + Object data; + Node next; + + private Node(Object o, Node l){ + this.next = l; + this.data = o; + } + } + + private class LinkedListIterator implements Iterator{ + private Node lastReturned; + private Node next; + private int nextIndex; + + LinkedListIterator(){ + next = LinkedList.this.head; + nextIndex = 0; + } + + @Override + public boolean hasNext() { + return nextIndex < size; + } + + @Override + public Object next() { + if (!hasNext()) + throw new NoSuchElementException(); + + lastReturned = next; + next = next.next; + nextIndex++; + return lastReturned.data; + } + + } +} diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/List.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/List.java new file mode 100644 index 0000000000..7268a54fbf --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/List.java @@ -0,0 +1,13 @@ +package com.zzl.util; + +public interface List { + public void add(Object o); + + public void add(int index, Object o); + + public Object get(int index); + + public Object remove(int index); + + public int size(); +} diff --git a/group13/1274639949/lesson01/src/com/hans/Queue.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java similarity index 55% rename from group13/1274639949/lesson01/src/com/hans/Queue.java rename to group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java index 2c696cca10..6e2869bd04 100644 --- a/group13/1274639949/lesson01/src/com/hans/Queue.java +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java @@ -1,19 +1,21 @@ -package com.hans; +package com.zzl.util; public class Queue { - private LinkedList elementData = new LinkedList(); + private ArrayList elementData = new ArrayList(); public void enQueue(Object o){ elementData.add(o); } public Object deQueue(){ - return elementData.removeFirst(); + return elementData.remove(0); } - + public boolean isEmpty(){ - return elementData.size() == 0; + int len = elementData.size(); + + return len == 0; } public int size(){ diff --git a/group27/514402862/dataStructure/src/main/java/com/zzl/util/Stack.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Stack.java new file mode 100644 index 0000000000..bcaf5fec95 --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Stack.java @@ -0,0 +1,40 @@ +package com.zzl.util; + +import java.util.EmptyStackException; + +public class Stack { + + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + Object o; + int len = elementData.size(); + + o = peek(); + elementData.remove(len - 1); + return o; + } + + public Object peek(){ + int len = elementData.size(); + + if(len == 0) + throw new EmptyStackException(); + + return elementData.get(len - 1); + } + + public boolean isEmpty(){ + int len = elementData.size(); + + return len == 0; + } + + public int size(){ + return elementData.size(); + } +} diff --git a/group27/514402862/dataStructure/src/test/java/com/zzl/util/ArrayListTest.java b/group27/514402862/dataStructure/src/test/java/com/zzl/util/ArrayListTest.java new file mode 100644 index 0000000000..14cf0f02e0 --- /dev/null +++ b/group27/514402862/dataStructure/src/test/java/com/zzl/util/ArrayListTest.java @@ -0,0 +1,100 @@ +package com.zzl.util; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class ArrayListTest { + + private List list; + private ArrayList aList; + + @Before + public void init() { + list = new ArrayList(); + + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + aList = new ArrayList(); + + aList.add("1"); + aList.add("2"); + aList.add("3"); + aList.add("4"); + aList.add("5"); + } + + @Test + public void testAddObject() { + + assertEquals(list.size(), 5); + } + + @Test + public void testAddIntObject() { + + list.add(2, "5"); + + assertEquals(list.get(2), "5"); + assertEquals(list.get(4), "4"); + } + + @Test + public void testGet() { + + String[] str = {"1","2","3","4","5"}; + Common.loop(list, str); + + list.add(4, "6"); + + String[] str1 = {"1","2","3","4","6","5"}; + Common.loop(list, str1); + } + + @Test + public void testRemove() { + + String[] str = {"1","2","4","5"}; + String result = Common.removeTest(list, 2, str); + list.add(2 ,result); + + String[] str1 = {"2","3","4","5"}; + result = Common.removeTest(list, 0, str1); + list.add(0 ,result); + + String[] str2 = {"1","2","3","4"}; + result = Common.removeTest(list, 4, str2); + list.add(4 ,result); + + String[] str3 = {"1","2","3","4","5"}; + Common.loop(list, str3); + } + + @Test + public void testIterator() { + + Iterator it = aList.iterator(); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "1"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "2"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "3"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "4"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "5"); + + assertFalse(it.hasNext()); + } +} diff --git a/group27/514402862/dataStructure/src/test/java/com/zzl/util/Common.java b/group27/514402862/dataStructure/src/test/java/com/zzl/util/Common.java new file mode 100644 index 0000000000..05eee18628 --- /dev/null +++ b/group27/514402862/dataStructure/src/test/java/com/zzl/util/Common.java @@ -0,0 +1,28 @@ +package com.zzl.util; + +import static org.junit.Assert.assertEquals; + +public class Common { + public static String removeTest(List list,int index, String[] str){ + assertEquals(list.size(), 5); + String result = (String)list.remove(index); + assertEquals(list.size(), 4); + + loop(list,str); + return result; + } + + public static void loop(List list,String[] str){ + for(int i = 0; i < list.size(); i++){ + assertEquals(list.get(i), str[i]); + } + } + + public static void loop(Stack s,String[] str){ + int len = s.size(); + for(int i = len - 1; i >= 0; i--){ + assertEquals(s.peek(), str[i]); + s.pop(); + } + } +} diff --git a/group27/514402862/dataStructure/src/test/java/com/zzl/util/LinkedListTest.java b/group27/514402862/dataStructure/src/test/java/com/zzl/util/LinkedListTest.java new file mode 100644 index 0000000000..c4820fee8b --- /dev/null +++ b/group27/514402862/dataStructure/src/test/java/com/zzl/util/LinkedListTest.java @@ -0,0 +1,103 @@ +package com.zzl.util; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +public class LinkedListTest { + + private List list; + private LinkedList aList; + + @Before + public void init() { + list = new LinkedList(); + + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + aList = new LinkedList(); + + aList.add("1"); + aList.add("2"); + aList.add("3"); + aList.add("4"); + aList.add("5"); + } + + @Test + public void testAddObject() { + assertEquals(list.size(), 5); + String[] str = {"1","2","3","4","5"}; + Common.loop(list, str); + } + + @Test + public void testAddIntObject() { + + list.add(3, "6"); + + assertEquals(list.get(3), "6"); + assertEquals(list.get(5), "5"); + + String[] str = {"1","2","3","6","4","5"}; + Common.loop(list, str); + } + + @Test + public void testRemove() { + + String[] str = {"1","2","4","5"}; + String result = Common.removeTest(aList, 2, str); + aList.add(2 ,result); + + String[] str1 = {"2","3","4","5"}; + result = Common.removeTest(aList, 0, str1); + aList.addFirst(result); + + String[] str2 = {"2","3","4","5"}; + aList.removeFirst(); + Common.loop(aList,str2); + aList.addFirst(result); + + String[] str3 = {"1","2","3","4"}; + result = Common.removeTest(aList, 4, str3); + aList.add(4 ,result); + + String[] str4 = {"1","2","3","4"}; + aList.removeLast(); + Common.loop(aList,str4); + aList.add(4 ,result); + + String[] str5 = {"1","2","3","4","5"}; + Common.loop(aList,str5); + } + + @Test + public void testIterator() { + + Iterator it = aList.iterator(); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "1"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "2"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "3"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "4"); + + assertTrue(it.hasNext()); + assertEquals(it.next(), "5"); + + assertFalse(it.hasNext()); + } +} diff --git a/group27/514402862/dataStructure/src/test/java/com/zzl/util/QueueTest.java b/group27/514402862/dataStructure/src/test/java/com/zzl/util/QueueTest.java new file mode 100644 index 0000000000..bc9da8f843 --- /dev/null +++ b/group27/514402862/dataStructure/src/test/java/com/zzl/util/QueueTest.java @@ -0,0 +1,44 @@ +package com.zzl.util; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class QueueTest { + + private Queue q; + + @Before + public void init() { + q = new Queue(); + + q.enQueue("1"); + q.enQueue("2"); + q.enQueue("3"); + q.enQueue("4"); + q.enQueue("5"); + } + + @Test + public void testEnQueue() { + assertEquals(q.size(), 5); + + q.deQueue(); + assertEquals(q.size(), 4); + } + + @Test + public void testIsEmpty() { + q = new Queue(); + + assertEquals(q.isEmpty(), true); + + q.enQueue("1"); + assertEquals(q.isEmpty(), false); + + q.deQueue(); + assertEquals(q.isEmpty(), true); + } + +} diff --git a/group27/514402862/dataStructure/src/test/java/com/zzl/util/StackTest.java b/group27/514402862/dataStructure/src/test/java/com/zzl/util/StackTest.java new file mode 100644 index 0000000000..e104c49f45 --- /dev/null +++ b/group27/514402862/dataStructure/src/test/java/com/zzl/util/StackTest.java @@ -0,0 +1,54 @@ +package com.zzl.util; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class StackTest { + + private Stack s; + + @Before + public void init() { + s = new Stack(); + + s.push("1"); + s.push("2"); + s.push("3"); + s.push("4"); + s.push("5"); + } + + @Test + public void testPush() { + assertEquals(s.size(), 5); + } + + @Test + public void testPop() { + s.pop(); + + assertEquals(s.size(), 4); + String[] str = {"1","2","3","4"}; + Common.loop(s, str); + } + + @Test + public void testPeek() { + String[] str = {"1","2","3","4","5"}; + Common.loop(s, str); + } + + @Test + public void testIsEmpty() { + assertFalse(s.isEmpty()); + + String[] str = {"1","2","3","4","5"}; + Common.loop(s, str); + assertTrue(s.isEmpty()); + + s.push("1"); + assertFalse(s.isEmpty()); + } +} diff --git a/group27/514402862/zzl.md b/group27/514402862/zzl.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/liuxin/src/com/coderising/litestruts/Struts.java b/liuxin/src/com/coderising/litestruts/Struts.java index 9761246bed..44cc35bf01 100644 --- a/liuxin/src/com/coderising/litestruts/Struts.java +++ b/liuxin/src/com/coderising/litestruts/Struts.java @@ -1,13 +1,11 @@ package com.coderising.litestruts; -import java.lang.reflect.Method; import java.util.Map; public class Struts { - public static View runAction(String actionName, Map parameters) { /* @@ -30,7 +28,6 @@ public static View runAction(String actionName, Map parameters) { */ - return null; }