diff --git a/.gitignore b/.gitignore index 77cdfba900..156b10d1f1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,29 +1,271 @@ - -build/ -.idea/ -.gradle/ -*.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 -*.DS_Store -liuxin/.DS_Store -liuxin/src/.DS_Store - + +################# +## 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 + +.recommenders +.idea/ +*.iml +rebel.* +.rebel.* + +target +*.DS_Store +liuxin/.DS_Store +liuxin/src/.DS_Store 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/group27/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs b/group10/904627477/.settings/org.eclipse.core.resources.prefs similarity index 64% rename from group27/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs rename to group10/904627477/.settings/org.eclipse.core.resources.prefs index 3e64772097..4824b80263 100644 --- a/group27/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs +++ b/group10/904627477/.settings/org.eclipse.core.resources.prefs @@ -1,3 +1,2 @@ -#Thu Mar 09 21:30:26 CST 2017 -eclipse.preferences.version=1 -encoding/=UTF-8 +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/group11/1178243325/DataStructure/src/main/java/com/coding/basic/List.java b/group10/904627477/src/com/coding/basic/List.java similarity index 100% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/List.java rename to group10/904627477/src/com/coding/basic/List.java 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/group11/1178243325/DataStructure/build.gradle b/group11/1178243325/DataStructure/build.gradle deleted file mode 100644 index 9c6bc859e6..0000000000 --- a/group11/1178243325/DataStructure/build.gradle +++ /dev/null @@ -1,20 +0,0 @@ - -apply plugin: 'java' -apply plugin: 'eclipse' - -jar { - from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }} - manifest { - attributes 'Main-Class' : 'com.Main' - } -} - -repositories { - mavenCentral() -} - -dependencies { - compile 'junit:junit:4.12' - compile 'dom4j:dom4j:1.6.1' -} - diff --git a/group11/1178243325/DataStructure/readme.md b/group11/1178243325/DataStructure/readme.md deleted file mode 100644 index 29ad9d5c06..0000000000 --- a/group11/1178243325/DataStructure/readme.md +++ /dev/null @@ -1 +0,0 @@ -实现基本的数据结构ArrayList,LinkList,Stack,Queue,Tree,Iterator diff --git a/group11/1178243325/DataStructure/src/main/java/com/Main.java b/group11/1178243325/DataStructure/src/main/java/com/Main.java deleted file mode 100644 index f5e5a36ebd..0000000000 --- a/group11/1178243325/DataStructure/src/main/java/com/Main.java +++ /dev/null @@ -1,56 +0,0 @@ -package com; - -import java.util.*; -import com.coderising.litestruts.*; -import com.coderising.array.*; -public class Main { - public static void main(String[] args) { - int[] array = {1, 2, 3, 4, 5}; - System.out.print("reverseArray测试:"); - ArrayUtil.reverseArray(array); - for (int i : array) - System.out.print(i + " "); - System.out.print("\nremoveZero测试:"); - - int[] oldArray = {1, 3, 4, 5, 0, 0, 8 , 0, 9}; - oldArray = ArrayUtil.removeZero(oldArray); - for (int i : oldArray) { - System.out.print(i + " "); - } - - System.out.print("\nmerge测试:"); - int[] a1 = {3, 5,8}; - int[] a2 = {4, 5, 6,7}; - int[] arrays = ArrayUtil.merge(a1, a2); - for (int i : arrays) - System.out.print(i + " "); - - System.out.print("\ngrow测试:"); - - int[] growArray = ArrayUtil.grow(a1, 5); - for (int i : growArray) - System.out.print(i + " "); - - System.out.print("\nfibonacci测试"); - int[] fArray = ArrayUtil.fibonacci(1); - System.out.print(fArray); - System.out.println(); - fArray = ArrayUtil.fibonacci(15); - for (int i : fArray) - System.out.print(i + " "); - System.out.print("\ngetPrimes测试:"); - int[] primesArray = ArrayUtil.getPrimes(23); - for (int i : primesArray) - System.out.print(i + " "); - System.out.print("\ngetPerfectNumbers测试:"); - int[] pArray = ArrayUtil.getPerfectNumbers(100); - for (int i : pArray) - System.out.print(i + " "); - System.out.print("\njoin测试:"); - int[] jArray = new int[]{2, 3, 8}; - System.out.print(ArrayUtil.join(jArray, "-")); - Map map = new HashMap<>(); - Struts.runAction("login", map); - - } -} diff --git a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/.Struts.java.swp b/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/.Struts.java.swp deleted file mode 100644 index 1f45a5f25e..0000000000 Binary files a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/.Struts.java.swp and /dev/null differ diff --git a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/Struts.java b/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/Struts.java deleted file mode 100644 index b3bd421435..0000000000 --- a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/Struts.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.coderising.litestruts; - -import java.util.Map; -import java.util.HashMap; -import java.lang.reflect.Method; -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 { - String targetClassName = XmlUtil.parseXML("struts.xml", actionName); - Class targetClass = Class.forName(targetClassName); - - Method setName = targetClass.getMethod("setName", String.class); - Method setPassword = targetClass.getMethod("setPassword", String.class); - Object object = targetClass.newInstance(); - - setName.invoke(object, parameters.get("name")); - setPassword.invoke(object, parameters.get("password")); - - Method execute = targetClass.getMethod("execute"); - String result = (String)execute.invoke(object); - - Method getMessage = targetClass.getMethod("getMessage"); - String message = (String)getMessage.invoke(object); - - Map params = new HashMap(); - params.put("message", message); - String jspUrl = XmlUtil.getJspUrl("struts.xml", actionName, result); - View view = new View(); - view.setJsp(jspUrl); - view.setParameters(params); - return view; - - } catch (Exception e) { - e.printStackTrace(); - } - - - return null; - } - -} diff --git a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/XmlUtil.java b/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/XmlUtil.java deleted file mode 100644 index d200452cc8..0000000000 --- a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/XmlUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.coderising.litestruts; - -import java.io.*; -import java.util.*; -import org.dom4j.Attribute; -import org.dom4j.Document; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; -public class XmlUtil { - - public static String parseXML(String filePath, String actionName) { - try { - File file = new File(filePath); - SAXReader reader = new SAXReader(); - Document doc = reader.read(file); - Element root = doc.getRootElement(); - for (Iterator iter = root.elementIterator("action"); iter.hasNext();) { - Element element = (Element)iter.next(); - Attribute nameAttr = element.attribute("name"); - if (nameAttr.getValue().equals(actionName)) { - Attribute classAttr = element.attribute("class"); - return classAttr.getValue(); - } - } - } catch (Exception e) { - e.printStackTrace(); - System.out.println("parse error"); - } - return null; - } - - public static String getJspUrl(String filePath, String actionName, String resultName) { - try { - File file = new File(filePath); - SAXReader reader = new SAXReader(); - Document doc = reader.read(file); - Element root = doc.getRootElement(); - for (Iterator iter = root.elementIterator("action"); iter.hasNext();) { - Element element = (Element)iter.next(); - Attribute nameAttr = element.attribute("name"); - if (nameAttr.getValue().equals(actionName)) { - for (Iterator ite = element.elementIterator("result"); ite.hasNext();) { - Element ele = (Element)ite.next(); - Attribute resultAttr = ele.attribute("name"); - if (resultAttr.getValue().equals(resultName)) { - return ele.getText(); - } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - -} diff --git a/group11/1178243325/week01/build.gradle b/group11/1178243325/week01/build.gradle new file mode 100644 index 0000000000..50d1380b3f --- /dev/null +++ b/group11/1178243325/week01/build.gradle @@ -0,0 +1,9 @@ +apply plugin: 'java' + +repositories { + mavenCentral(); +} + +dependencies { + testCompile("junit:junit:4.12") +} diff --git a/group11/1178243325/week01/readme.md b/group11/1178243325/week01/readme.md new file mode 100644 index 0000000000..314098dd59 --- /dev/null +++ b/group11/1178243325/week01/readme.md @@ -0,0 +1,16 @@ +## 讲课内容: +- 17-2-15: 社群kickoff +- 17-2-19:讲解Java自测题和基本数据结构 +- 17-2-22:计算机组成原理和计算机编程语言 +- 17-2-26:程序的机器级表示 + +## 第一周作业(2-15 至 2-26) +- 实现各种基本数据结构(ArrayList, Stack, LinkedList, Queue, Tree, Iterator) +- 写一篇介绍CPU,内存,硬盘,指令以及他们之间的关系 + +## 完成情况: +- 基本数据结构已完成 +- [文章地址](http://www.jianshu.com/p/8d8379aa1281) + +## 我的收获: +- [漫谈计算机组成原理和编程语言](http://www.jianshu.com/p/07df48adf338) diff --git a/group11/1178243325/week01/src/main/java/com/sprint/basic/Iterator.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/Iterator.java new file mode 100644 index 0000000000..1e73a2a4b9 --- /dev/null +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/Iterator.java @@ -0,0 +1,6 @@ +package com.sprint.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); +} diff --git a/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/ConcurrentModificationException.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/ConcurrentModificationException.java new file mode 100644 index 0000000000..c91c388bbd --- /dev/null +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/ConcurrentModificationException.java @@ -0,0 +1,9 @@ +package com.sprint.basic.exception; + +public class ConcurrentModificationException extends RuntimeException { + public ConcurrentModificationException() {} + public ConcurrentModificationException(String msg) { + super(msg); + } +} + diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyQueueException.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyQueueException.java similarity index 81% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyQueueException.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyQueueException.java index 2ee7aa4ee7..ddf89ac120 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyQueueException.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyQueueException.java @@ -1,4 +1,4 @@ -package com.coding.basic.exception; +package com.sprint.basic.exception; public class EmptyQueueException extends RuntimeException { public EmptyQueueException() {} diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyStackException.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyStackException.java similarity index 81% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyStackException.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyStackException.java index 2a5ae4055d..d654c7cd16 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/EmptyStackException.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/exception/EmptyStackException.java @@ -1,4 +1,4 @@ -package com.coding.basic.exception; +package com.sprint.basic.exception; public class EmptyStackException extends RuntimeException { public EmptyStackException() {} diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/ArrayList.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/ArrayList.java similarity index 86% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/ArrayList.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/list/ArrayList.java index f6cd4c38fc..fb64e93f36 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/ArrayList.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/ArrayList.java @@ -1,6 +1,7 @@ -package com.coding.basic; +package com.sprint.basic.list; -import com.coding.basic.exception.*; +import com.sprint.basic.exception.ConcurrentModificationException; +import com.sprint.basic.Iterator; public class ArrayList implements List { private int size; @@ -11,11 +12,12 @@ public ArrayList () { elementData = new Object[100]; } - public void add(Object o){ + public boolean add(Object o) { add(size(), o); + return true; } - public void add(int index, Object o){ + public boolean add(int index, Object o){ if (size() == elementData.length) ensureCapacity( size() * 2 + 1); if (index > size() || index < 0) { //index == size时相当于在尾后插入 @@ -26,7 +28,7 @@ public void add(int index, Object o){ } elementData[index] = o; size++; - + return true; } private void ensureCapacity(int newCapacity) { diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/LinkedList.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/LinkedList.java similarity index 72% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/LinkedList.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/list/LinkedList.java index d82349089b..503f41f65b 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/LinkedList.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/LinkedList.java @@ -1,6 +1,8 @@ -package com.coding.basic; +package com.sprint.basic.list; -import com.coding.basic.exception.*; +import com.sprint.basic.exception.ConcurrentModificationException; +import com.sprint.basic.Iterator; +import java.util.Objects; public class LinkedList implements List { private Node head; @@ -10,11 +12,12 @@ public LinkedList() { size = 0; } - public void add(Object o){ + public boolean add(Object o) { add(size, o); + return true; } - public void add(int index , Object o){ + public boolean add(int index , Object o) { if (index > size || index < 0) { throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } @@ -22,9 +25,10 @@ public void add(int index , Object o){ Node newNode = new Node(o, frontNode.next); frontNode.next = newNode; size++; - + return true; } + /*getNode getPreNodeByElement getNextNodeByElement的效率低些*/ private Node getNode(int index) { Node node = head; int i = 0; @@ -35,6 +39,28 @@ private Node getNode(int index) { return node; } + private Node getPreNodeByElement(Object obj) { + if (obj != null) { + for (int i = 0; i < size(); i++) { + if (getNode(i).data == obj) { + return getNode(i-1); + } + } + } + return null; + } + + private Node getNextNodeByElement(Object obj) { + if (obj != null) { + for (int i = 0; i < size(); i++) { + if (getNode(i).data == obj) { + return getNode(i+1); + } + } + } + return null; + } + public Object get(int index){ if (index >= size || index < 0) { throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); @@ -60,7 +86,6 @@ public int size(){ } public void addFirst(Object o){ - //就是这么硬! add(0, o); } diff --git a/group11/1178243325/week01/src/main/java/com/sprint/basic/list/List.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/List.java new file mode 100644 index 0000000000..0e90471a48 --- /dev/null +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/list/List.java @@ -0,0 +1,10 @@ +package com.sprint.basic.list; +import com.sprint.basic.Iterator; +public interface List { + public boolean add(Object o); + public boolean add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); + public Iterator iterator(); +} diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/Queue.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/queue/Queue.java similarity index 62% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/Queue.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/queue/Queue.java index a5c31f5a09..47f7b98d96 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/Queue.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/queue/Queue.java @@ -1,5 +1,6 @@ -package com.coding.basic; -import com.coding.basic.exception.*; +package com.sprint.basic.queue; +import com.sprint.basic.exception.EmptyQueueException; +import com.sprint.basic.list.LinkedList; public class Queue { private LinkedList elementData; @@ -8,8 +9,9 @@ public Queue() { elementData = new LinkedList(); } - public void enQueue(Object o){ - elementData.addLast(o); + public boolean enQueue(Object o){ + elementData.addLast(o); + return true; } public Object deQueue(){ diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/Stack.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/stack/Stack.java similarity index 72% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/Stack.java rename to group11/1178243325/week01/src/main/java/com/sprint/basic/stack/Stack.java index e41c662792..e399dcb850 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/Stack.java +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/stack/Stack.java @@ -1,6 +1,7 @@ -package com.coding.basic; +package com.sprint.basic.stack; -import com.coding.basic.exception.*; +import com.sprint.basic.exception.EmptyStackException; +import com.sprint.basic.list.ArrayList; public class Stack { private ArrayList elementData; @@ -8,8 +9,9 @@ public Stack() { elementData = new ArrayList(); } - public void push(Object o){ + public boolean push(Object o){ elementData.add(o); + return true; } public Object pop(){ diff --git a/group11/1178243325/week01/src/main/java/com/sprint/basic/tree/BinaryTreeNode.java b/group11/1178243325/week01/src/main/java/com/sprint/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..efaf261521 --- /dev/null +++ b/group11/1178243325/week01/src/main/java/com/sprint/basic/tree/BinaryTreeNode.java @@ -0,0 +1,122 @@ +package com.sprint.basic.tree; + +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 BinaryTreeNode insert(T data) { + if (this.data == null) { + this.data = data; + return this; + } + int compareResult = this.data.compareTo(data); + if (compareResult > 0) { + if (this.left == null) { + this.left = new BinaryTreeNode(); + this.left.data = data; + return this.left; + } else { + return this.left.insert(data); + } + } else if (compareResult < 0) { + if (this.right == null) { + this.right = new BinaryTreeNode(); + this.right.data = data; + return this.right; + } else { + return this.right.insert(data); + } + } else { + return this; + } + } + + /*没看懂*/ + public BinaryTreeNode delete(T data) { + BinaryTreeNode treeNode = search(data); + if (treeNode == null) { + return null; + } + int compareResult = this.data.compareTo(data); + if (compareResult > 0) { + return this.left.delete(data); + } else if (compareResult < 0) { + return this.right.delete(data); + } else { + if (treeNode.right == null) { + if (this.left == null) { + this.data = null; + } else { + this.left = this; + } + } else { + this.data = (T) this.right.findMin().data; + + this.right.delete(this.data); + } + } + + return this; + } + + private BinaryTreeNode findMin() { + if (this.data == null) { + return null; + } + if (this.left == null) { + return this; + } + return this.left.findMin(); + } + + public BinaryTreeNode search(T data) { + if (this.data == null) { + return null; + } + int compareResult = this.data.compareTo(data); + if (compareResult > 0) { + if (this.left == null) { + return null; + } else { + return this.left.search(data); + } + } else if (compareResult < 0) { + if (this.right == null) { + return null; + } else { + return this.right.search(data); + } + } else { + return this; + } + } + + +} diff --git a/group11/1178243325/week01/src/test/java/com/sprint/basic/list/ArrayListTest.java b/group11/1178243325/week01/src/test/java/com/sprint/basic/list/ArrayListTest.java new file mode 100644 index 0000000000..63936c288c --- /dev/null +++ b/group11/1178243325/week01/src/test/java/com/sprint/basic/list/ArrayListTest.java @@ -0,0 +1,56 @@ +package com.sprint.basic.list; + +import com.sprint.basic.Iterator; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ArrayListTest { + private List list; + + @Before + public void init() { + list = new ArrayList(); + } + + @Test + public void add() { + for (int i = 0; i < 5; i++) { + list.add(i); + } + /*Assert.assertTrue(args): if (args != true) to failed*/ + System.out.println(list); + Assert.assertTrue(list.add(5)); + Assert.assertEquals(6, list.size()); + Assert.assertTrue(list.add(3, 10)); + Assert.assertEquals(7, list.size()); + + } + + @Test + public void remove() { + add(); + Assert.assertEquals(5, list.remove(6)); + Assert.assertEquals(6, list.size()); + } + + @Test + public void get() { + add(); + Assert.assertEquals(5, list.get(6)); + } + + @Test + public void testIterator() { + for (int i = 0; i < 10; i++) { + Assert.assertTrue(list.add(i)); + } + Iterator iter = list.iterator(); + int count = 0; + while(iter.hasNext()) { + Assert.assertEquals(count, iter.next()); + count++; + } + } + +} diff --git a/group11/1178243325/week01/src/test/java/com/sprint/basic/list/LinkedListTest.java b/group11/1178243325/week01/src/test/java/com/sprint/basic/list/LinkedListTest.java new file mode 100644 index 0000000000..c5ab12aa4e --- /dev/null +++ b/group11/1178243325/week01/src/test/java/com/sprint/basic/list/LinkedListTest.java @@ -0,0 +1,56 @@ +package com.sprint.basic.list; + +import com.sprint.basic.Iterator; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class LinkedListTest { + private List list; + + @Before + public void init() { + list = new LinkedList(); + } + + @Test + public void add() { + for (int i = 0; i < 5; i++) { + list.add(i); + } + /*Assert.assertTrue(args): if (args != true) to failed*/ + System.out.println(list); + Assert.assertTrue(list.add(5)); + Assert.assertEquals(6, list.size()); + Assert.assertTrue(list.add(3, 10)); + Assert.assertEquals(7, list.size()); + + } + + @Test + public void remove() { + add(); + Assert.assertEquals(5, list.remove(6)); + Assert.assertEquals(6, list.size()); + } + + @Test + public void get() { + add(); + Assert.assertEquals(5, list.get(6)); + } + + @Test + public void testIterator() { + for (int i = 0; i < 10; i++) { + Assert.assertTrue(list.add(i)); + } + Iterator iter = list.iterator(); + int count = 0; + while(iter.hasNext()) { + Assert.assertEquals(count, iter.next()); + count++; + } + } + +} diff --git a/group11/1178243325/week01/src/test/java/com/sprint/basic/queue/QueueTest.java b/group11/1178243325/week01/src/test/java/com/sprint/basic/queue/QueueTest.java new file mode 100644 index 0000000000..b7cfe4b32f --- /dev/null +++ b/group11/1178243325/week01/src/test/java/com/sprint/basic/queue/QueueTest.java @@ -0,0 +1,20 @@ +package com.sprint.basic.queue; + +import org.junit.Assert; +import org.junit.Test; +public class QueueTest { + + private Queue queue = new Queue(); + + @Test + public void testQueueApi() { + Assert.assertTrue(queue.enQueue(1)); + Assert.assertTrue(queue.enQueue(2)); + Assert.assertFalse(queue.isEmpty()); + Assert.assertEquals(2, queue.size()); + Assert.assertEquals(1, queue.deQueue()); + Assert.assertEquals(2, queue.deQueue()); + Assert.assertEquals(0, queue.size()); + Assert.assertTrue(queue.isEmpty()); + } +} diff --git a/group11/1178243325/week01/src/test/java/com/sprint/basic/stack/StackTest.java b/group11/1178243325/week01/src/test/java/com/sprint/basic/stack/StackTest.java new file mode 100644 index 0000000000..e267c59971 --- /dev/null +++ b/group11/1178243325/week01/src/test/java/com/sprint/basic/stack/StackTest.java @@ -0,0 +1,23 @@ +package com.sprint.basic.stack; + +import org.junit.Assert; +import org.junit.Test; + +public class StackTest { + + private Stack stack = new Stack(); + + @Test + public void testStack() { + Assert.assertTrue(stack.push(1)); + Assert.assertEquals(1, stack.pop()); + Assert.assertTrue(stack.push(2)); + Assert.assertTrue(stack.push(3)); + Assert.assertTrue(stack.push(4)); + Assert.assertEquals(4, stack.pop()); + Assert.assertEquals(2, stack.peek()); + Assert.assertEquals(2, stack.size()); + Assert.assertFalse(stack.isEmpty()); + } + +} diff --git a/group11/1178243325/week01/src/test/java/com/sprint/basic/tree/BinaryTreeNodeTest.java b/group11/1178243325/week01/src/test/java/com/sprint/basic/tree/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..d9a27ab211 --- /dev/null +++ b/group11/1178243325/week01/src/test/java/com/sprint/basic/tree/BinaryTreeNodeTest.java @@ -0,0 +1,54 @@ +package com.sprint.basic.tree; + +import org.junit.Assert; +/*参考程序*/ +public class BinaryTreeNodeTest { + + private BinaryTreeNode treeNode; + + @org.junit.Before + public void setUp() throws Exception { + treeNode = new BinaryTreeNode<>(); + treeNode.insert(5); + treeNode.insert(3); + treeNode.insert(7); + treeNode.insert(1); + treeNode.insert(4); + treeNode.insert(2); + treeNode.insert(8); + treeNode.insert(6); + } + + @org.junit.Test + public void insert() { + Assert.assertEquals(treeNode.getData().intValue(), 5); + Assert.assertEquals(treeNode.getLeft().getData(), 3); + Assert.assertEquals(treeNode.getRight().getData(), 7); + Assert.assertEquals(treeNode.getLeft().getLeft().getData(), 1); + Assert.assertEquals(treeNode.getLeft().getRight().getData(), 4); + Assert.assertEquals(treeNode.getLeft().getLeft().getRight().getData(), 2); + Assert.assertEquals(treeNode.getRight().getRight().getData(), 8); + Assert.assertEquals(treeNode.getRight().getLeft().getData(), 6); + } + + @org.junit.Test + public void delete() throws Exception { + treeNode.delete(3); + for (int i = 1; i < 9; i++) { + if (i != 3) { + Assert.assertNotNull(treeNode.search(i)); + } else { + Assert.assertNull(treeNode.search(i)); + } + } + } + + @org.junit.Test + public void search() throws Exception { + for (int i = 1; i < 9; i++) { + Assert.assertNotNull(treeNode.search(i)); + } + Assert.assertNull(treeNode.search(0)); + Assert.assertNull(treeNode.search(9)); + } +} diff --git a/group11/1178243325/week02/build.gradle b/group11/1178243325/week02/build.gradle new file mode 100644 index 0000000000..f6ebbb892e --- /dev/null +++ b/group11/1178243325/week02/build.gradle @@ -0,0 +1,12 @@ +apply plugin: 'java' + + +repositories { + maven { url "http://maven.aliyun.com/nexus/content/groups/public" } + mavenCentral() +} + +dependencies { + compile("org.jdom:jdom2:2.0.5") + testCompile("junit:junit:4.12") +} diff --git a/group11/1178243325/week02/readme.md b/group11/1178243325/week02/readme.md new file mode 100644 index 0000000000..a4f9adc15a --- /dev/null +++ b/group11/1178243325/week02/readme.md @@ -0,0 +1,23 @@ +## 讲课内容: +- 17-03-01:第一周作业讲评 +- 17-03-05:漫谈进程和线程和布置第三周作业 + +## 第二周作业(2-27 至 3-5) +- 实现第一个大作业:读取struts.xml,执行Action +- 5道数据结构习题 + +## 完成情况: +- struts大作业完成 +- 数据结构习题完成 + +## 我的收获: +- TDD +- 操作系统抽象概念 +- 进程在虚拟存储器表示 +- 进程调度 +- 进程同步 +- 线程 + + +![99.jpg](http://upload-images.jianshu.io/upload_images/2031765-d3740acf4d284e93.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) + diff --git a/group11/1178243325/DataStructure/src/main/java/com/coderising/array/ArrayUtil.java b/group11/1178243325/week02/src/main/java/com/sprint/array/ArrayUtil.java similarity index 93% rename from group11/1178243325/DataStructure/src/main/java/com/coderising/array/ArrayUtil.java rename to group11/1178243325/week02/src/main/java/com/sprint/array/ArrayUtil.java index f94d5d01c4..01d7d5f0da 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coderising/array/ArrayUtil.java +++ b/group11/1178243325/week02/src/main/java/com/sprint/array/ArrayUtil.java @@ -1,4 +1,4 @@ -package com.coderising.array; +package com.sprint.array; public class ArrayUtil { @@ -32,7 +32,7 @@ public static void reverseArray(int[] origin){ public static int[] removeZero(int[] oldArray){ if (oldArray == null) { - return null; + return new int[0]; } int zeroCount = 0; @@ -60,7 +60,7 @@ public static int[] removeZero(int[] oldArray){ public static int[] merge(int[] array1, int[] array2){ if (array1 == null && array2 == null) - return null; + return new int[0]; int index1 = 0, index2 = 0; int[] array3 = new int[array1.length + array2.length]; int index = 0; @@ -101,7 +101,7 @@ public static int[] merge(int[] array1, int[] array2){ */ public static int[] grow(int [] oldArray, int size){ if (size <= 0) - return null; + return new int[0]; int[] newArray = new int[oldArray.length + size]; for (int i = 0; i < oldArray.length; i++) { newArray[i] = oldArray[i]; @@ -118,9 +118,9 @@ public static int[] grow(int [] oldArray, int size){ */ public static int[] fibonacci(int max){ if (max < 1) - return null; + return new int[0]; if (max == 1) - return null; + return new int[0]; int[] array = new int[max]; int i = 0; int value = fibonaccis(i+1); @@ -151,7 +151,7 @@ private static int fibonaccis(int n) { */ public static int[] getPrimes(int max){ if (max <= 1) { - return null; + return new int[0]; } int[] array = new int[max]; int index = 0; @@ -177,7 +177,7 @@ public static int[] getPrimes(int max){ */ public static int[] getPerfectNumbers(int max){ if (max <= 0) - return null; + return new int[0]; int[] array = new int[max]; int index = 0; for (int i = 1; i < max; i++) { diff --git a/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Configuration.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Configuration.java new file mode 100644 index 0000000000..0f10458fc3 --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Configuration.java @@ -0,0 +1,86 @@ +package com.sprint.litestruts; + +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) { + InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName); + parseXML(is); + try { + is.close(); + } catch (IOException e) { + throw new ConfigurationException(e); + } + } + + 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); + } + } + + public String getClassName(String actionName) { + ActionConfig ac = this.actions.get(actionName); + 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 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/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ConfigurationException.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ConfigurationException.java new file mode 100644 index 0000000000..25c6784f43 --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ConfigurationException.java @@ -0,0 +1,18 @@ +package com.sprint.litestruts; + +import java.io.IOException; +import org.jdom2.JDOMException; +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/group11/1178243325/week02/src/main/java/com/sprint/litestruts/LoginAction.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/LoginAction.java new file mode 100644 index 0000000000..4b4f2b8e38 --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/LoginAction.java @@ -0,0 +1,40 @@ +package com.sprint.litestruts; + +/** + * 这是一个展示业务逻辑的类,其中用户名是硬编码 + * @author xingzhaohu + */ + +public class LoginAction { + private String name; + private String password; + private String message; + + 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 getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String getMessage() { + return message; + } +} diff --git a/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtil.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtil.java new file mode 100644 index 0000000000..822355655b --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtil.java @@ -0,0 +1,70 @@ +package com.sprint.litestruts; + +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException; +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 List getGetterMethods(Class clz) { + return getMethods(clz, "get"); + } + + 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; + } + + 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 e) { + throw new ReflectionUtilException(e); + } catch (IllegalArgumentException e) { + throw new ReflectionUtilException(e); + } catch (InvocationTargetException e) { + throw new ReflectionUtilException(e); + } + } + } + } + + } + + 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 e) { + throw new ReflectionUtilException(e); + } catch (IllegalArgumentException e) { + throw new ReflectionUtilException(e); + } catch (InvocationTargetException e) { + throw new ReflectionUtilException(e); + } + } + return params; + } + +} diff --git a/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtilException.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtilException.java new file mode 100644 index 0000000000..65cbfdf322 --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/ReflectionUtilException.java @@ -0,0 +1,20 @@ +package com.sprint.litestruts; + +import java.lang.reflect.InvocationTargetException; +public class ReflectionUtilException extends RuntimeException { + + public ReflectionUtilException(String msg) { + super(msg); + } + public ReflectionUtilException(IllegalAccessException e) { + super(e); + } + + public ReflectionUtilException(IllegalArgumentException e) { + super(e); + } + + public ReflectionUtilException(InvocationTargetException e) { + super(e); + } +} diff --git a/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Struts.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Struts.java new file mode 100644 index 0000000000..bff4dec33b --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/Struts.java @@ -0,0 +1,53 @@ +package com.sprint.litestruts; + +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); + + Map params = ReflectionUtil.getParameterMap(action); + String resultView = cfg.getResultView(actionName, resultName); + View view = new View(); + view.setParameters(params); + view.setJsp(resultView); + return view; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/group11/1178243325/week02/src/main/java/com/sprint/litestruts/View.java b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/View.java new file mode 100644 index 0000000000..fb380de515 --- /dev/null +++ b/group11/1178243325/week02/src/main/java/com/sprint/litestruts/View.java @@ -0,0 +1,24 @@ +package com.sprint.litestruts; + +import java.util.Map; +public class View { + private String jsp; + private Map parameters; + + public void setJsp(String jsp) { + this.jsp = jsp; + } + + public String getJsp() { + return jsp; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + public Map getParameters() { + return parameters; + } + +} diff --git a/group11/1178243325/week02/src/main/resources/struts.xml b/group11/1178243325/week02/src/main/resources/struts.xml new file mode 100644 index 0000000000..c82c7d1574 --- /dev/null +++ b/group11/1178243325/week02/src/main/resources/struts.xml @@ -0,0 +1,12 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + + diff --git a/group11/1178243325/week02/src/test/java/com/sprint/array/ArrayUtilTest.java b/group11/1178243325/week02/src/test/java/com/sprint/array/ArrayUtilTest.java new file mode 100644 index 0000000000..9cba21f7cf --- /dev/null +++ b/group11/1178243325/week02/src/test/java/com/sprint/array/ArrayUtilTest.java @@ -0,0 +1,76 @@ +package com.sprint.array; + +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Test; +public class ArrayUtilTest { + + @Test + public void testReverseArray() { + int[] a = new int[]{7, 9, 30, 3}; + int[] expected = new int[]{3, 30, 9, 7}; + ArrayUtil.reverseArray(a); + Assert.assertArrayEquals(a, expected); + a = new int[]{7, 9, 30, 3, 4}; + expected = new int[]{4, 3, 30, 9, 7}; + ArrayUtil.reverseArray(a); + Assert.assertArrayEquals(a, expected); + } + + @Test + public void testRemoveZero() { + int[] oldArr = new int[]{1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; + int[] expected = new int[]{1,3,4,5,6,6,5,4,7,6,7,5}; + Assert.assertArrayEquals(ArrayUtil.removeZero(oldArr), expected); + oldArr = new int[]{1, 0, 2, 0, 3, 0}; + expected = new int[]{1, 2, 3}; + Assert.assertArrayEquals(ArrayUtil.removeZero(oldArr), expected); + } + + @Test + public void testMerge() { + int[] a1 = {3, 5, 7, 8}; + int[] a2 = {4, 5, 6, 7}; + int[] a3 = {3, 4, 5, 6, 7, 8}; + Assert.assertArrayEquals(ArrayUtil.merge(a1, a2), a3); + } + + @Test + public void testGrow() { + int[] oldArray = new int[]{2, 3, 6}; + int[] expected = new int[]{2, 3, 6, 0, 0, 0}; + Assert.assertArrayEquals(ArrayUtil.grow(oldArray, 3), expected); + } + + @Test + public void testFibonacci() { + int[] expected = new int[]{1, 1, 2, 3, 5, 8, 13}; + Assert.assertArrayEquals(ArrayUtil.fibonacci(15), expected); + expected = new int[0]; + Assert.assertArrayEquals(ArrayUtil.fibonacci(1), expected); + /*GET 新技能: [] == new int[0]*/ + System.out.println(Arrays.toString(expected)); + } + + @Test + public void testGetPrimes() { + int[] expected = new int[]{2,3,5,7,11,13,17,19}; + Assert.assertArrayEquals(ArrayUtil.getPrimes(23), expected); + } + + @Test + public void testGetPerfectNumbers() { + int[] result = new int[]{6}; + int length = ArrayUtil.getPerfectNumbers(7).length; + System.out.println(length); + Assert.assertArrayEquals(ArrayUtil.getPerfectNumbers(7), result); + } + + @Test + public void tetJoin() { + String result = "3-8-9"; + int[] array = {3, 8, 9}; + Assert.assertEquals(ArrayUtil.join(array, "-"), result); + } + +} diff --git a/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ConfigurationTest.java b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ConfigurationTest.java new file mode 100644 index 0000000000..f4b5f91668 --- /dev/null +++ b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ConfigurationTest.java @@ -0,0 +1,31 @@ +package com.sprint.litestruts; + +import org.junit.Test; +import org.junit.Assert; +public class ConfigurationTest { + Configuration cfg = new Configuration("struts.xml"); + + @Test + public void testGetClassName() { + String clzName = cfg.getClassName("login"); + Assert.assertEquals("com.sprint.litestruts.LoginAction", clzName); + clzName = cfg.getClassName("logout"); + Assert.assertEquals("com.sprint.litestruts.LoginAction", 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); + } + +} diff --git a/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ReflectionUtilTest.java b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ReflectionUtilTest.java new file mode 100644 index 0000000000..c6fb04bda6 --- /dev/null +++ b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/ReflectionUtilTest.java @@ -0,0 +1,92 @@ +package com.sprint.litestruts; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Set; +import java.util.Map; + + +import org.junit.Test; +import org.junit.Assert; +public class ReflectionUtilTest { + + @Test + public void testGetSetterMethod() throws Exception{ + String name = "com.sprint.litestruts.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 acctualNames = new HashSet<>(); + for (Method m : methods) { + acctualNames.add(m.getName()); + } + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testGetGetterMethod() throws Exception { + String name = "com.sprint.litestruts.LoginAction"; + Class clz = Class.forName(name); + List methods = ReflectionUtil.getGetterMethods(clz); + + Assert.assertEquals(3, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("getName"); + expectedNames.add("getPassword"); + expectedNames.add("getMessage"); + + Set acctualNames = new HashSet<>(); + for (Method m : methods) { + acctualNames.add(m.getName()); + } + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testSetParameters() throws Exception { + String name = "com.sprint.litestruts.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 testGetParameters() throws Exception { + String name = "com.sprint.litestruts.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")); + + } + +} diff --git a/group11/1178243325/week02/src/test/java/com/sprint/litestruts/StrutsTest.java b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/StrutsTest.java new file mode 100644 index 0000000000..d8c68d2807 --- /dev/null +++ b/group11/1178243325/week02/src/test/java/com/sprint/litestruts/StrutsTest.java @@ -0,0 +1,32 @@ +package com.sprint.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/group11/1178243325/week03/build.gradle b/group11/1178243325/week03/build.gradle new file mode 100644 index 0000000000..c4da624f95 --- /dev/null +++ b/group11/1178243325/week03/build.gradle @@ -0,0 +1,9 @@ +apply plugin: 'java' + +repositories { + mavenCentral() +} + +dependencies { + testCompile("junit:junit:4.12") +} diff --git a/group11/1178243325/week03/readme.md b/group11/1178243325/week03/readme.md new file mode 100644 index 0000000000..e418f46fd6 --- /dev/null +++ b/group11/1178243325/week03/readme.md @@ -0,0 +1,16 @@ +## 讲课内容: +- 17-03-07:答疑(YY) +- 17-03-09:TDD和第二次作业讲解 +- 17-03-12:职场15年 + +## 第二周作业(3-6 至 3-12) +- 实现第二个大作业:多线程下载文件,支持断点续传 +- 5道数据结构习题 + +## 完成情况: +- 多线程完成 +- 待重构 + +## 我的收获: +- TTD大法好 +- 面向对象的思想以及抽象化,更深刻 diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/Iterator.java b/group11/1178243325/week03/src/main/java/com/sprint/basic/Iterator.java similarity index 100% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/Iterator.java rename to group11/1178243325/week03/src/main/java/com/sprint/basic/Iterator.java diff --git a/group11/1178243325/week03/src/main/java/com/sprint/basic/LinkedList.java b/group11/1178243325/week03/src/main/java/com/sprint/basic/LinkedList.java new file mode 100644 index 0000000000..ac4128fe80 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/basic/LinkedList.java @@ -0,0 +1,319 @@ +package com.sprint.basic; + +import com.sprint.basic.exception.ConcurrentModificationException; +import java.util.Objects; +public class LinkedList implements List { + + private Node head; + private int size; + public LinkedList() { + head = new Node(null, null); + size = 0; + } + + public void add(Object o){ + add(size, o); + } + + public void add(int index , Object o){ + if (index > size || index < 0) { + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + } + Node frontNode = getNode(index-1); + Node newNode = new Node(o, frontNode.next); + frontNode.next = newNode; + size++; + + } + + /*getNode getPreNodeByElement getNextNodeByElement的效率低些*/ + private Node getNode(int index) { + Node node = head; + int i = 0; + while(node.next != null && i <= index) { + node = node.next; + i++; + } + return node; + } + + private Node getPreNodeByElement(Object obj) { + if (obj != null) { + for (int i = 0; i < size(); i++) { + if (getNode(i).data == obj) { + return getNode(i-1); + } + } + } + return null; + } + + private Node getNextNodeByElement(Object obj) { + if (obj != null) { + for (int i = 0; i < size(); i++) { + if (getNode(i).data == obj) { + return getNode(i+1); + } + } + } + return null; + } + public Object get(int index){ + if (index >= size || index < 0) { + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + } + + Node node = getNode(index); + return node.data; + } + + public Object remove(int index){ + if (index >= size || index < 0) { + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + } + Node frontNode = getNode(index-1); + Node oldNode = getNode(index); + frontNode.next = oldNode.next; + size--; + return oldNode.data; + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + add(0, o); + } + + public void addLast(Object o){ + add(size, o); + } + + public Object removeFirst(){ + return remove(0); + } + + public Object removeLast(){ + return remove(size-1); + } + + public Iterator iterator(){ + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator { + int index; + final int capacity = size; + LinkedListIterator() { + index = 0; + } + @Override + public boolean hasNext() { + if (capacity != size) + throw new ConcurrentModificationException("此对象没有修改同步"); + return index < capacity; + } + + @Override + public Object next() { + if (capacity != size) + throw new ConcurrentModificationException("此对象没有修改同步"); + if (index >= capacity) + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + return get(index++); + } + } + + private String outOfBoundsMsg(int index) { + return "index:" + index + ", size:" + size; + } + + private static class Node { + Object data; + Node next; + + Node(Object data, Node next) { + this.data = data; + this.next = next; + } + + void setData(Object data) { + this.data = data; + } + + Object getData() { + return data; + } + + void setNext(Node next) { + this.next = next; + } + + Object getNext() { + return next; + } + } + + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + Object[] oldData = new Object[size]; + Node temp = head; + int index = 1; + while(temp.next != null) { + temp = temp.next; + oldData[size - index] = temp.data; + index++; + } + + index = 0; + temp = head; + while(temp.next != null) { + temp = temp.next; + temp.data = oldData[index]; + index++; + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + + public void removeFirstHalf(){ + int count = size; + if (count % 2 != 0) { + for (int i = 0; i <= count/2; i++) { + removeFirst(); + } + } else { + for (int i = 0; i < count/2; i++) { + removeFirst(); + } + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + + public void remove(int i, int length){ + if (i < 0 || length < 0) { + return; + } + if (i == 0) { + for (int k = 0; k < length; k++) + removeFirst(); + } else { + while (length > 0) { + remove(i-1); + 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){ + if (list.size() == 0) { + return new int[0]; + } + int[] array = new int[list.size()]; + int index = 0; + for (int i = 0; i < list.size(); i++) { + array[i] = (int)get((int)list.get(i)); + } + return array; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + public void subtract(LinkedList list){ + if (list.size() == 0) { + return; + } + for (int i = 0; i < list.size(); i++) { + removeElement(list.get(i)); + } + } + + private Object removeElement(Object obj) { + if (obj == null) { + return null; + } + Node preNode = getPreNodeByElement(obj); + Node nextNode = getNextNodeByElement(obj); + if (preNode == null && nextNode == null) + return null; + preNode.next = nextNode; + return obj; + } + + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + + public void removeDuplicateValues(){ + if (size == 0 || size == 1) { + return; + } + + Node p1 = head; + Node p2 = head.next; + + while (p1 != null && p2 != null) { + if (Objects.equals(p1.data, p2.data)) { + p2 = p2.next; + p1.next = p2; + size--; + } else { + p1 = p2; + p2 = p2.next; + } + } + } + + + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于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/liuxin/src/com/coding/basic/List.java b/group11/1178243325/week03/src/main/java/com/sprint/basic/List.java similarity index 100% rename from liuxin/src/com/coding/basic/List.java rename to group11/1178243325/week03/src/main/java/com/sprint/basic/List.java diff --git a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/ConcurrentModificationException.java b/group11/1178243325/week03/src/main/java/com/sprint/basic/exception/ConcurrentModificationException.java similarity index 100% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/exception/ConcurrentModificationException.java rename to group11/1178243325/week03/src/main/java/com/sprint/basic/exception/ConcurrentModificationException.java diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/DownloadThread.java b/group11/1178243325/week03/src/main/java/com/sprint/download/DownloadThread.java new file mode 100644 index 0000000000..434b60e7be --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/DownloadThread.java @@ -0,0 +1,36 @@ +package com.sprint.download; + +import com.sprint.download.api.Connection; +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; +public class DownloadThread extends Thread { + Connection conn; + int startPos; + int endPos; + CyclicBarrier barrier; + String localFile; + public DownloadThread(Connection conn, int startPos, int endPos, + String localFile, CyclicBarrier barrier) { + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.localFile = localFile; + this.barrier = barrier; + } + + @Override + public void run() { + try { + System.out.println("Begin to read [" + startPos + "-" + endPos + "]"); + byte[] data = conn.read(startPos, endPos); + RandomAccessFile file = new RandomAccessFile(localFile, "rw"); + file.seek(startPos); + file.write(data); + file.close(); + conn.close(); + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/FileDownloader.java b/group11/1178243325/week03/src/main/java/com/sprint/download/FileDownloader.java new file mode 100644 index 0000000000..9a817aefaf --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/FileDownloader.java @@ -0,0 +1,89 @@ +package com.sprint.download; + +import com.sprint.download.api.Connection; +import com.sprint.download.api.ConnectionManager; +import com.sprint.download.api.DownloadListener; +import java.util.concurrent.CyclicBarrier; +import java.io.RandomAccessFile; +import java.io.IOException; +public class FileDownloader { + private String url; + private String localFile; + + DownloadListener listener; + ConnectionManager cm; + + private static final int DOWNLOAD_THREAD_NUM = 3; + + public FileDownloader(String _url, String localFile) { + this.url = _url; + this.localFile = localFile; + } + + public void execute() { + CyclicBarrier barrier = new CyclicBarrier(DOWNLOAD_THREAD_NUM, new Runnable() { + public void run() { + listener.notifyFinished(); + } + }); + + Connection conn = null; + + try { + conn = cm.open(this.url); + int length = conn.getContentLength(); + createPlaceHolderFile(this.localFile, length); + int[][] ranges = allocateDownloadRange(DOWNLOAD_THREAD_NUM, length); + for (int i = 0; i < DOWNLOAD_THREAD_NUM; i++) { + DownloadThread thread = new DownloadThread( + cm.open(url), + ranges[i][0], + ranges[i][1], + localFile, + barrier); + thread.start(); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + private void createPlaceHolderFile(String fileName, int contentLen) throws IOException { + RandomAccessFile file = new RandomAccessFile(fileName, "rw"); + for (int i = 0; i < contentLen; i++) { + file.write(0); + } + file.close(); + } + + private int[][] allocateDownloadRange(int threadNum, int contentLen) { + int[][] ranges = new int[threadNum][2]; + int eachThreadSize = contentLen / threadNum; + int left = contentLen % threadNum; + for (int i = 0; i < threadNum; i++) { + int startPos = i*eachThreadSize; + int endPos = (i+1) * eachThreadSize - 1; + if (i == (threadNum -1)) { + endPos += left; + } + ranges[i][0] = startPos; + ranges[i][1] = endPos; + } + return ranges; + } + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public DownloadListener getListener() { + return listener; + } +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/api/Connection.java b/group11/1178243325/week03/src/main/java/com/sprint/download/api/Connection.java new file mode 100644 index 0000000000..958a0b1ce3 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/api/Connection.java @@ -0,0 +1,26 @@ +package com.sprint.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/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionException.java b/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionException.java new file mode 100644 index 0000000000..f9ec627440 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionException.java @@ -0,0 +1,7 @@ +package com.sprint.download.api; + +public class ConnectionException extends Exception { + public ConnectionException(Exception e) { + super(e); + } +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionManager.java b/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionManager.java new file mode 100644 index 0000000000..f20bbacc87 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/api/ConnectionManager.java @@ -0,0 +1,11 @@ +package com.sprint.download.api; + +public interface ConnectionManager { + /** + * 给定一个url, 打开一个连接 + * @param url + * @return + */ + + public Connection open(String url) throws ConnectionException; +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/api/DownloadListener.java b/group11/1178243325/week03/src/main/java/com/sprint/download/api/DownloadListener.java new file mode 100644 index 0000000000..fc95ba8199 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.sprint.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionImpl.java b/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..c6c1f32cb4 --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionImpl.java @@ -0,0 +1,68 @@ +package com.sprint.download.impl; + +import com.sprint.download.api.Connection; +import com.sprint.download.api.ConnectionException; +import java.util.Arrays; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.HttpURLConnection; + +public class ConnectionImpl implements Connection { + + URL url; + static final int BUFFER_SIZE = 1024; + + ConnectionImpl(String _url) throws ConnectionException { + try { + url = new URL(_url); + } catch (MalformedURLException e) { + throw new ConnectionException(e); + } + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + httpConn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + + InputStream is = httpConn.getInputStream(); + byte[] buff = new byte[BUFFER_SIZE]; + int totalLen = endPos - startPos + 1; + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while (baos.size() < totalLen) { + int len = is.read(buff); + if (len < 0) { + break; + } + baos.write(buff, 0, len); + } + + if (baos.size() > totalLen) { + byte[] data = baos.toByteArray(); + return Arrays.copyOf(data, totalLen); + } + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + URLConnection con; + try { + con = url.openConnection(); + return con.getContentLength(); + } catch (IOException e) { + e.printStackTrace(); + } + return -1; + } + + @Override + public void close() { + + } +} diff --git a/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionManagerImpl.java b/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..7a012808ef --- /dev/null +++ b/group11/1178243325/week03/src/main/java/com/sprint/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,14 @@ +package com.sprint.download.impl; + +import com.sprint.download.api.Connection; +import com.sprint.download.api.ConnectionException; +import com.sprint.download.api.ConnectionManager; +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + return new ConnectionImpl(url); + } +} + + diff --git a/group11/1178243325/week03/src/test/java/com/sprint/download/FileDownloaderTest.java b/group11/1178243325/week03/src/test/java/com/sprint/download/FileDownloaderTest.java new file mode 100644 index 0000000000..6e3bccd2dc --- /dev/null +++ b/group11/1178243325/week03/src/test/java/com/sprint/download/FileDownloaderTest.java @@ -0,0 +1,41 @@ +package com.sprint.download; + +import com.sprint.download.api.ConnectionManager; +import com.sprint.download.api.DownloadListener; +import com.sprint.download.impl.ConnectionManagerImpl; + +import org.junit.Assert; +import org.junit.Test; +public class FileDownloaderTest { + boolean downloadFinished = false; + + @Test + public void testDownload() { + String url = "http://images2015.cnblogs.com/blog/610238/201604/610238-20160421154632101-286208268.png"; + FileDownloader downloader = new FileDownloader(url, "/home/sprint/xxx/test.jpg");// 保存地址时我的本地地址 + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = false; + } + }); + + downloader.execute(); + + //等待多线程下载 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + } +} diff --git a/group11/1178243325/week03/src/test/java/com/sprint/download/api/ConnectionTest.java b/group11/1178243325/week03/src/test/java/com/sprint/download/api/ConnectionTest.java new file mode 100644 index 0000000000..4322814936 --- /dev/null +++ b/group11/1178243325/week03/src/test/java/com/sprint/download/api/ConnectionTest.java @@ -0,0 +1,21 @@ +package com.sprint.download.api; + +import com.sprint.download.impl.ConnectionManagerImpl; +import org.junit.Assert; +import org.junit.Test; +public class ConnectionTest { + + @Test + public void testGetContentLength() throws Exception { + ConnectionManager connMan = new ConnectionManagerImpl(); + Connection conn = connMan.open("http://www.hinews.cn/pic/0/13/91/26/13912621_821796.jpg"); + Assert.assertEquals(35470, conn.getContentLength()); + } + + @Test + public void testRead() throws Exception { + ConnectionManager connMan = new ConnectionManagerImpl(); + Connection conn = connMan.open("http://www.hinews.cn/pic/0/13/91/26/13912621_821796.jpg"); + + } +} diff --git a/group11/1178243325/week04/readme.md b/group11/1178243325/week04/readme.md new file mode 100644 index 0000000000..2199199aef --- /dev/null +++ b/group11/1178243325/week04/readme.md @@ -0,0 +1,12 @@ +## 讲课内容: +- 17-03-15:第三次作业讲解 +- 17-03-19:Edison分享的职业发展 + +## 第四周作业(3-13 至 3-19) +无,调整进度 + +## 完成情况: +休养生息 + +## 我的收获: +- 职业发展:从新人到老兵 diff --git a/group11/1178243325/week05/readme.md b/group11/1178243325/week05/readme.md new file mode 100644 index 0000000000..d4388e66d7 --- /dev/null +++ b/group11/1178243325/week05/readme.md @@ -0,0 +1,13 @@ +## 讲课内容: +- 17-03-22 :漫谈操作系统之虚拟内存 +- 17-03-26 :概要性介绍class文件结构和字节码的执行过程 + +## 第五周作业(3-20 至 3-26) +无,调整进度 + +## 完成情况: +修养生息 + +## 我的收获: +- 虚拟内存 +- 进一步理解JVM diff --git a/group11/1310368322/GitHub/.gitignore b/group11/1310368322/GitHub/.gitignore deleted file mode 100644 index 5e56e040ec..0000000000 --- a/group11/1310368322/GitHub/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin diff --git a/group11/1310368322/GitHub/src/testGitHub.java b/group11/1310368322/GitHub/src/testGitHub.java deleted file mode 100644 index af74e99b53..0000000000 --- a/group11/1310368322/GitHub/src/testGitHub.java +++ /dev/null @@ -1,7 +0,0 @@ - -public class testGitHub { - private void mian() { - System.out.print("Hello GitHub"); - } - -} diff --git a/group11/1310368322/GitHub/src/ArrayList.java b/group11/1310368322/src/FirstHomework/BaseDataStructure/ArrayList.java similarity index 62% rename from group11/1310368322/GitHub/src/ArrayList.java rename to group11/1310368322/src/FirstHomework/BaseDataStructure/ArrayList.java index 68b42b1c03..b5024f1dfb 100644 --- a/group11/1310368322/GitHub/src/ArrayList.java +++ b/group11/1310368322/src/FirstHomework/BaseDataStructure/ArrayList.java @@ -1,18 +1,31 @@ -package Day_2017_2_20_DateStructure; +package Day_2017_2_26_FirstHomework; public class ArrayList { - + private static final int DEFAULT_SIZE = 10; + private static final int MAX_VALUE = 2147483647; + private Object[] elementData = new Object[DEFAULT_SIZE]; + private Exception Exception; private int size = 0; + + public ArrayList(){ + this(DEFAULT_SIZE); + } + public ArrayList(int defaultSize) { + rangCheckForConstructor(defaultSize); + elementData = new Object[defaultSize]; + } - private Object[] elementData = new Object[10]; - private Exception Exception; + private void rangCheckForConstructor(int defaultSize) { + if(defaultSize<0 || defaultSize>MAX_VALUE){ + throw new IndexOutOfBoundsException("ֵ"); + } + + } public void add(Object o){ - if(size>elementData.length){ - elementData = ArrayList.grow(elementData, 10); - } + ensureCapacity(); for(int i = 0; i < elementData.length; i++){ if(null == elementData[i]){ elementData[i] = o; @@ -21,13 +34,14 @@ public void add(Object o){ } size++; } - public void add(int index, Object o){ + private void ensureCapacity() { if(size>elementData.length){ elementData = ArrayList.grow(elementData, 10); } - if(index<0){ - System.out.println("λ"); - } + } + public void add(int index, Object o){ + rangeCheckForAdd(index); + ensureCapacity(); int k = -1; for(int i = index; i < elementData.length; i++){ if(null==elementData[i]){ @@ -41,6 +55,12 @@ public void add(int index, Object o){ elementData[index] = o; size++; } + private void rangeCheckForAdd(int index) { + if(index < 0 || index > this.size){// add Ԫֻ [0,size](ԸsizeλòԪأԸsizeԪ) + throw new IndexOutOfBoundsException("±Խ"); + } + + } public Object get(int index){ return elementData[index]; } @@ -72,7 +92,6 @@ public static Object[] grow(Object[] elementData2, int size){ public static void main(String[] args) { ArrayList a = new ArrayList(); - a.add("a"); a.getElementData(); System.out.println(a.size); } diff --git a/group11/1310368322/src/FirstHomework/BaseDataStructure/LinkedList.java b/group11/1310368322/src/FirstHomework/BaseDataStructure/LinkedList.java new file mode 100644 index 0000000000..488f2a22a6 --- /dev/null +++ b/group11/1310368322/src/FirstHomework/BaseDataStructure/LinkedList.java @@ -0,0 +1,113 @@ +package Day_2017_2_26_FirstHomework; + +public class LinkedList{ + private Node head; + static int size = 0; + public void add(Object o){ + if(null == head){ + head = new Node(); + head.data = o; + head.next = null; + }else{ + Node p = head; + while(null != p.next){ + p = p.next; + } + Node newNode = new Node(); + newNode.data = o; + p.next = newNode; + newNode.next =null; + } + size++; + } + public int size(){ + return size; + } + public void add(int index,Object o){ + if(index < 0){ + throw new RuntimeException("±겻Ϊ"); + } + if(index == 0){ + addFirst(o); + size++; + return; + } + if(index > size){ + throw new RuntimeException(""); + } + int i = 0; + Node p = head; + Node q = null; + + while(i!=index){ + q = p; + p = p.next; + i++; + } + Node r = new Node(); + r.data = o; + r.next =null; + q.next = r; + r.next = p; + size++; + return; + } + + public Object get(int index){ + int i = 0; + Node p = head; + while(i != index){ + p = p.next; + i++; + } + return p.data; + } + public Object remove(int index){ + if(index < 0){ + throw new RuntimeException("±겻Ϊ"); + } + if(index == 1){ + size--; + return head.data; + } + int i = 0; + Node p = head; + Node q = null; + while(i != index){ + q = p; + p = p.next; + i++; + } + q.next = p.next; + size--; + return p.data; + } + public void addFirst(Object o){ + Node p = new Node(); + p.next = head; + p.data = o; + head = p; + size++; + } + public Object removeFirst(){ + head = head.next; + size--; + return null; + } + public static class Node{ + Object data; + Node next; + } + + public static void main(String[] args) { + LinkedList linkedList = new LinkedList(); + linkedList.add("a"); + linkedList.add("b"); + linkedList.add("c"); + linkedList.add("d"); + linkedList.add(5, "f"); + System.out.println(linkedList.get(5)); + System.out.println(linkedList.size()); + } + +} \ No newline at end of file diff --git a/group11/1310368322/src/SecondHomework/BaseDataStructure/ArrayUtil.java b/group11/1310368322/src/SecondHomework/BaseDataStructure/ArrayUtil.java new file mode 100644 index 0000000000..81bc431679 --- /dev/null +++ b/group11/1310368322/src/SecondHomework/BaseDataStructure/ArrayUtil.java @@ -0,0 +1,83 @@ +package day_2017_2_26_SecondHomework; + +import java.util.Arrays; + +import javax.management.RuntimeErrorException; + +public class ArrayUtil { + + /* * + * һ a Ըֵû + * 磺 a = [7, 9, 30, 3], ûΪ [3, 30, 9, 7] + * */ + + /*public ArrayUtil(int[] a2) { + this.a = a2; + }*/ + public void reverseArray(int [] a){ + if(null == a){ + System.out.println("ָ----"); + return; + } + int temp; + int last = a.length-1; + for (int i = 0; i < a.length/2; i++) { + temp = a[i]; + a[i] = a[last]; + a[last--] = temp; + } + } + public void print(int [] a){ + if(null == a){ + System.out.println("ָ----"); + return; + } + for (int i = 0; i < a.length; i++) { + System.out.print(a[i] + " "); + } + System.out.println(); + } + + /* * + * µһ飬 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; + } + int count = 0; + int oldArrayLength = oldArray.length; + for(int i = 0; i < oldArrayLength;){ + if(oldArray[i]==0){ + for(int j = i; j < oldArrayLength -1; j++){ + oldArray[j] = oldArray[j+1]; + } + oldArrayLength--; + count++; + }else{ + i++; + } + } + int [] target = new int[oldArray.length-count]; + System.arraycopy(oldArray, 0, target, 0, oldArray.length-count); + return target; + } + + + + + + + + + + + + + + +} diff --git a/group11/1310368322/src/ThirdHomework/BaseDataStructure/LinkedList.java b/group11/1310368322/src/ThirdHomework/BaseDataStructure/LinkedList.java new file mode 100644 index 0000000000..5ea6a988be --- /dev/null +++ b/group11/1310368322/src/ThirdHomework/BaseDataStructure/LinkedList.java @@ -0,0 +1,162 @@ +package DataStructure_3; + +import java.util.Stack; + +import DataStructure_1.LinkedList.Node; + +public class LinkedList { + private Node head; + static int size = 0; + public void add(Object o){ + if(null == head){ + head = new Node(); + head.data = o; + head.next = null; + }else{ + Node p = head; + while(null != p.next){ + p = p.next; + } + Node newNode = new Node(); + newNode.data = o; + p.next = newNode; + newNode.next =null; + } + size++; + } + public int size(){ + return size; + } + public void add(int index,Object o){ + if(index < 0){ + throw new RuntimeException("±겻Ϊ"); + } + if(index == 0){ + addFirst(o); + size++; + return; + } + if(index > size){ + throw new RuntimeException(""); + } + int i = 0; + Node p = head; + Node q = null; + + while(i!=index){ + q = p; + p = p.next; + i++; + } + Node r = new Node(); + r.data = o; + r.next =null; + q.next = r; + r.next = p; + size++; + return; + } + + public Object get(int index){ + int i = 0; + Node p = head; + while(i != index){ + p = p.next; + i++; + } + return p.data; + } + public Object remove(int index){ + if(index < 0){ + throw new RuntimeException("±겻Ϊ"); + } + if(index == 1){ + size--; + return head.data; + } + int i = 0; + Node p = head; + Node q = null; + while(i != index){ + q = p; + p = p.next; + i++; + } + q.next = p.next; + size--; + return p.data; + } + public void addFirst(Object o){ + Node p = new Node(); + p.next = head; + p.data = o; + head = p; + size++; + } + public Object removeFirst(){ + head = head.next; + size--; + return null; + } + public static class Node{ + Object data; + Node next; + } + + /** + * Ѹ + * 3->7->10 úΪ 10->7->3 + */ + public void reverse(){ + if(null == head || null == head.next){ + return; + } + Stack s = new Stack(); + Node curNode = head; + while(curNode != null){ + s.push(curNode); + Node nextNode = curNode.next; + curNode.next = null; // Ͽ + curNode = nextNode; + } + + head = s.pop(); + curNode = head; + while(!s.isEmpty()){ + Node nextNode = s.pop(); + curNode.next = nextNode; + curNode = nextNode; + } + + } + + public String toString(){ + StringBuffer buffer = new StringBuffer(); + buffer.append("["); + Node node = head; + while(node != null){ + buffer.append(node.data); + if(node.next != null){ + buffer.append(","); + } + node = node.next; + } + buffer.append("]"); + return buffer.toString(); + } + + + + + + + + + + + + + + + +} diff --git a/group11/1310368322/src/ThirdHomework/Download/DownloadThread.java b/group11/1310368322/src/ThirdHomework/Download/DownloadThread.java new file mode 100644 index 0000000000..af248b72b2 --- /dev/null +++ b/group11/1310368322/src/ThirdHomework/Download/DownloadThread.java @@ -0,0 +1,39 @@ +package day_2017_3_8_ThreadHomework; + +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + CyclicBarrier barrier; + String localFile; + public DownloadThread(Connection conn, int startPos, int endPos,String localFile,CyclicBarrier barrier){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.localFile = localFile; + this.barrier = barrier; + } + public void run(){ + try { + System.out.println("Begin to read [" + startPos + "-" + endPos + "]"); + byte [] data = conn.read(startPos, endPos); + System.out.println("һȡļĶ"); + RandomAccessFile file = new RandomAccessFile(localFile,"rw"); + file.seek(startPos); + System.out.println("Ҫд"); + file.write(data); + file.close(); + conn.close(); + System.out.println(this.currentThread().getName()+"once over"); + barrier.await(); + } catch (Exception e) { + // TODO: handle exception + } + } +} diff --git a/group11/1310368322/src/ThirdHomework/Download/FileDownloader.java b/group11/1310368322/src/ThirdHomework/Download/FileDownloader.java new file mode 100644 index 0000000000..445ede2e3d --- /dev/null +++ b/group11/1310368322/src/ThirdHomework/Download/FileDownloader.java @@ -0,0 +1,114 @@ +package day_2017_3_8_ThreadHomework; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + +public class FileDownloader { + private String url; + private String localFile; + DownloadListener listener; + ConnectionManager cm; + + private static final int DOWNLOAD_THREAD_NUM = 3; + public FileDownloader(String _url,String localFile){ + this.url = _url; + this.localFile = localFile; + } + + public void execute(){ + // ʵĴ룬 ע⣺ Ҫö߳ʵ + // ӿڣҪд⼸ӿڵʵִ + // 1 ConnectionManager ԴһӣͨConnectionԶȡеһΣStartPos,endPosָ + // 2DownloadListener, Ƕ߳أĿͻ˲֪ʲôʱҪʵ̶ִֵ߳Ժ󣬵listenernotifiedFinishedͻ˾յ֪ͨ + // ʵ˼· + // 1. ҪConnectionManager open ӣȻͨ Connection.getContentLengthļij + // 2. 3߳أעÿ߳ҪȵConnectionManageropen + // Ȼ read read жȡļĿʼλúͽλõIJֵbyte[] + // 3. byte д뵽ļ + // 4.е̶߳ԺҪ listener notifiedFinished + + // Ĵʵ룬Ҳ˵ֻһ̣߳Ҫɶ̵߳ + CyclicBarrier barrier = new CyclicBarrier(DOWNLOAD_THREAD_NUM,new Runnable() {// еThread awaitʱִк barrierAction,ú߳ + @Override + public void run() { + listener.notifyFinished(); + } + }); + + Connection conn = null; + try { + conn = cm.open(this.url); + int length = conn.getContentLength();// õҪļij + createPlaceHolderFile(this.localFile,length);//ռλ + System.out.println("ռλ"); + int [][] ranges = allocateDownloadRange(DOWNLOAD_THREAD_NUM,length);// ÿ̷߳俪ʼλúͽλ + // ʼļ + System.out.println("ʼļ"); + for(int i = 0; i < DOWNLOAD_THREAD_NUM; i++){ + DownloadThread thread = new DownloadThread( + cm.open(url), + ranges[i][0], + ranges[i][1], + localFile, + barrier); + thread.start(); + System.out.println("" + (i+1) + "߳Ѿ"); + } + + } catch (Exception e) { + e.printStackTrace(); + }finally{ + System.out.println("ر"); + if(conn != null){ + conn.close(); + System.out.println("رӳɹ"); + } + } + } + + public void setListener(DownloadListener listener){ + this.listener = listener; + } + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + public DownloadListener getListener(){ + return this.listener; + } + private void createPlaceHolderFile(String fileName,int contentLen) throws IOException{ + RandomAccessFile file = new RandomAccessFile(fileName,"rw"); + for(int i = 0; i < contentLen; i++){ + file.write(0); + } + file.close(); + } + /** + * ߳ļȣһά飬ÿ߳صĿʼλúͽλ + * @param threadNum + * @param contentLen + * @return + */ + private int [][] allocateDownloadRange(int threadNum, int contentLen){ + int [][] ranges = new int[threadNum][2];// öάÿ̵߳Ŀʼλúͽλ + + int eachThreadSize = contentLen / threadNum;// ÿ߳ҪصļС + int left = contentLen % threadNum;// ʣµĹһ߳ + + for(int i = 0; i totalLen){ + byte[] data = baos.toByteArray(); + return Arrays.copyOf(data, totalLen); + } + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + URLConnection con; + try { + con = url.openConnection(); + return con.getContentLength(); + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } + + @Override + public void close() { + + } + +} diff --git a/group11/1310368322/src/ThirdHomework/Download/impl/ConnectionManagerImpl.java b/group11/1310368322/src/ThirdHomework/Download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..ff92aa77fe --- /dev/null +++ b/group11/1310368322/src/ThirdHomework/Download/impl/ConnectionManagerImpl.java @@ -0,0 +1,16 @@ +package com.coderising.download.impl; + +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 { + return new ConnectionImpl(url); + } + +} diff --git a/group11/1310368322/test/SecondHomwork/BaseDataStructure/ArrayUtilTest.java b/group11/1310368322/test/SecondHomwork/BaseDataStructure/ArrayUtilTest.java new file mode 100644 index 0000000000..aaf3a80e7e --- /dev/null +++ b/group11/1310368322/test/SecondHomwork/BaseDataStructure/ArrayUtilTest.java @@ -0,0 +1,101 @@ +package day_2017_2_26_SecondHomework; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ArrayUtilTest { + ArrayUtil arrayUtil; + + @Before + public void setUp() throws Exception { + arrayUtil = new ArrayUtil(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testReverseArray_a() { + int [] actuals = {}; + int [] expected = {}; + arrayUtil.reverseArray(actuals); + Assert.assertArrayEquals(expected, actuals); + } + @Test + public void testReverseArray_b() { + int [] actuals = null; + int [] expected = null; + arrayUtil.reverseArray(actuals); + Assert.assertArrayEquals(expected, actuals); + } + @Test + public void testReverseArray_c() { + int [] actuals = {1,2,3,4}; + int [] expected = {4,3,2,1}; + arrayUtil.reverseArray(actuals); + Assert.assertArrayEquals(expected, actuals); + } + + + @Test + public void testRemoveZero_1(){ + int [] actuals = null; + int [] expected = null; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + @Test + public void testRemoveZero_2(){ + int [] actuals = {}; + int [] expected = {}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + @Test + public void testRemoveZero_3(){ + int [] actuals = {0,0,0,0,0,0}; + int [] expected = {}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + @Test + public void testRemoveZero_4(){ + int [] actuals = {1,2,3,4,5,6}; + int [] expected = {1,2,3,4,5,6}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + @Test + public void testRemoveZero_5(){ + int [] actuals = {1,2,0,0,5,6}; + int [] expected = {1,2,5,6}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + @Test + public void testRemoveZero_6(){ + int [] actuals = {0,0,4,2}; + int [] expected = {4,2}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + }@Test + public void testRemoveZero_7(){ + int [] actuals = {4,2,0,0,0}; + int [] expected = {4,2}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + public void testRemoveZero_8(){ + int [] actuals = {0,0,4,0,0,2,0,0,0}; + int [] expected = {4,2}; + int [] actual = arrayUtil.removeZero(actuals); + Assert.assertArrayEquals(expected, actual); + } + + +} diff --git a/group11/1310368322/test/ThirdHomework/BaseDataStructure/TestLinkedList.java b/group11/1310368322/test/ThirdHomework/BaseDataStructure/TestLinkedList.java new file mode 100644 index 0000000000..343f9d6f39 --- /dev/null +++ b/group11/1310368322/test/ThirdHomework/BaseDataStructure/TestLinkedList.java @@ -0,0 +1,25 @@ +package DataStructure_3; + +import static org.junit.Assert.*; +import org.junit.Assert; +import org.junit.Test; + +public class TestLinkedList { + + @Test + public void test() { + LinkedList L = new LinkedList(); + Assert.assertEquals("[]", L.toString()); + + L.add(1); + L.reverse(); + Assert.assertEquals("[1]", L.toString()); + + L.add(2); + L.add(3); + L.add(4); + L.reverse(); + Assert.assertEquals("[4,3,2,1]",L.toString()); + } + +} diff --git a/group11/1310368322/test/ThirdHomework/Download/FileDownloaderTest.java b/group11/1310368322/test/ThirdHomework/Download/FileDownloaderTest.java new file mode 100644 index 0000000000..f337778812 --- /dev/null +++ b/group11/1310368322/test/ThirdHomework/Download/FileDownloaderTest.java @@ -0,0 +1,44 @@ +package testDownload; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +import day_2017_3_8_ThreadHomework.FileDownloader; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Test + public void test() { + String url = "http://pic33.nipic.com/2013 0916/3420027_192919547000_2.jpg"; + FileDownloader downloader = new FileDownloader(url,"d:/test.jpg"); + 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 (Exception e) { + e.printStackTrace(); + } + } + System.out.println(""); + } + + +} diff --git a/group11/171535320/DataStruct/ArrayList.java b/group11/171535320/DataStruct/ArrayList.java index 4340deecf4..5bed84f633 100644 --- a/group11/171535320/DataStruct/ArrayList.java +++ b/group11/171535320/DataStruct/ArrayList.java @@ -3,7 +3,7 @@ import java.util.Arrays; import java.util.Objects; -public class ArrayList implements List { +public class ArrayList implements List { private int size = 0; diff --git a/group11/171535320/DataStruct/LinkedList.java b/group11/171535320/DataStruct/LinkedList.java index 24a99466ca..9aa9fbc46c 100644 --- a/group11/171535320/DataStruct/LinkedList.java +++ b/group11/171535320/DataStruct/LinkedList.java @@ -1,7 +1,5 @@ package DataStruct; -import DataStruct.List; - public class LinkedList implements List { private Node head; @@ -151,4 +149,185 @@ private static class Node{ Node next; } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + Node first = head; + Node last = head.next; + while(last != null) { + Node temp = last; + last = last.next; + temp.next = first; + first = temp; + } + head = first; + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + Node temp = head; + int len = 1; + while(temp.next != null) { + temp = temp.next; + len++; + } + + int num = len / 2; + + for(int i = 0; i < num; ++i) { + head = head.next; + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + if(i == 0) { + head = null; + } + Node temp = head; + for(int n = 1; n < i; ++n) { + temp = temp.next; + } + Node last = temp; + for(int n = 0; n < length; ++n) { + if(last != null) { + last = last.next; + } + } + temp.next = last; + + } + /** + * 假定当前链表和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){ + ArrayList tempList = new ArrayList(); + Node t = head; + int i = 0; + while(t != null) { + tempList.add((Integer) t.data); + i++; + } + int k = 0; + int[] result = new int[i]; + for(int j = 0; j < list.size(); ++j) { + result[k++] = (Integer)tempList.get((Integer) list.get(j)); + } + return result; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + + public void subtract(java.util.LinkedList list){ + Node temp = head; + Node temp2 = head; + int i = 0; + + while(i < list.size() || temp != null) { + if(i == list.size() || temp == null) { + break; + } + if(list.get(i) > (Integer)temp.data) { + temp2 = temp; + temp = temp.next; + } else if(list.get(i) < (Integer)temp.data) { + i++; + } else { + temp2.next = temp.next; + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + Node temp1 = head; + Node temp2 = head.next; + while(temp2 != null) { + if(temp1.data == temp2.data) { + temp2 = temp2.next; + } else { + temp1.next = temp2; + temp1 = temp2; + temp2 = temp2.next; + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + Node first = head; + Node first2 = first; + Node last = head.next; + Node last2 = last; + while(last != null) { + if((Integer)last.data < max && (Integer)first.data < min) { + first2 = first; + first = first.next; + last2 = last; + last = last.next; + } else if((Integer)last.data > max && (Integer)first.data > min) { + break; + } else if((Integer)last.data < max && (Integer)first.data > min) { + last2 = last; + last = last.next; + } else { + first2 = first; + first = first.next; + } + } + first2.next = last; + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + LinkedList result = new LinkedList(); + Node temp = head; + Node temp2 = list.head; + while(temp != null && temp2 != null) { + if((Integer)temp.data == (Integer)temp2.data) { + result.add(temp.data); + temp = temp.next; + temp2 = temp2.next; + } else if((Integer)temp.data > (Integer)temp2.data) { + temp2 = temp2.next; + } else { + temp = temp.next; + } + } + + return result; + } } diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic/List.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic/List.java index daa8253313..82e72e1080 100644 --- a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic/List.java +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic/List.java @@ -6,19 +6,9 @@ */ public interface List { - boolean add(Object o); - - boolean add(int index, Object o); - - Object set(int index, Object element); - + void add(Object o); + void add(int index, Object o); Object get(int index); - Object remove(int index); - int size(); - - boolean isEmpty(); - - Iterator iterator(); } diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic2/LinkedList.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic2/LinkedList.java new file mode 100644 index 0000000000..5286f27746 --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/basic2/LinkedList.java @@ -0,0 +1,429 @@ +package org.pan.coding2017.basic2; + +import org.pan.coding2017.basic.Iterator; +import org.pan.coding2017.basic.List; + +public class LinkedList implements List { + + private Node head; + private Node tail; + private int size=0; + + private void checkIndex(int index){ + if(index<0 || index>=this.size) + { + throw new IndexOutOfBoundsException("Error!Invalid index:"+index); + } + } + + private void checkSize(){ + if(size==0) + { + throw new RuntimeException("Empty LinkedList."); + } + } + + public void add(Object o){ + Node temp = new Node(o,null); + if(this.head==null){ + this.head = temp; + this.tail = head; + }else{ + this.tail.next = temp; + this.tail = temp; + } + this.size++; + } + + /* (non-Javadoc) + * @see com.coding.basic2.List#add(int, java.lang.Object) + */ + public void add(int index , Object o){ + checkIndex(index); + if(index==0) + { + Node newNode = new Node(o,head); + head = newNode; + }else{ + Node temp = head; + for(int i=1;i0){ + Node temp = head; + sb.append(temp.data); + while(temp.hasNext()){ + temp = temp.next; + sb.append(","); + sb.append(temp.data); + } + } + return sb.toString(); + } + + public Object remove(int index){ + checkIndex(index); + Node temp = head; + Node pre = head; + Object result; + if(index == 0) + { + result = head.data; + head = head.next; + }else{ + for(int i=0;i0) + { + pre=pre.next; + } + temp=temp.next; + } + result = temp.data; + pre.next=temp.next; + temp = null; + + + if(index == size-1) + { + tail = pre; + } + } + size--; + + return result; + } + + public int size(){ + return this.size; + } + + public void addFirst(Object o){ + Node temp = new Node(o,head); + head = temp; + size++; + + } + public void addLast(Object o){ + Node temp = new Node(o,null); + tail.next = temp; + tail = temp; + size++; + } + public Object removeFirst(){ + return remove(0); + } + public Object removeLast(){ + return remove(size-1); + } + public Iterator iterator(){ + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator{ + private Node current = head; + + @Override + public boolean hasNext() + { + return current!=null; + } + + @Override + public Object next() { + if(current==null) + { + throw new RuntimeException("Current element has not next."); + } + + Object result = current.data; + current = current.next; + return result; + } + + @Override + public void remove() { + + } + + } + + + private static class Node{ + Object data; + Node next; + public boolean hasNext(){ + return (this.next!=null); + } + + public Node(Object data,Node next){ + this.data=data; + this.next=next; + } + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + checkSize(); + int tempSize = size; + Node temp = new Node(removeFirst(),null); + tail = temp; + while(size>0){ + temp = new Node(removeFirst(),temp); + } + head = temp; + size = tempSize; + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + checkSize(); + if(size>1) + { + int temp = size; + for(int i=0;isize-i) + { + throw new RuntimeException("No enough size to remove from index:"+i); + }else{ + for(int j=0;j101->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]; + }else{ + int[] result = new int[list.size()]; + Node temp = head; + int currentPos = 0; + for(int i=0;ival){ + break; + }else if(tempVal==val){ + remove(j); + break; + }else{ + continue; + } + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + Node temp = head; + while(temp!=null){ + while(temp.hasNext()&&temp.data.equals(temp.next.data)) + { + temp.next = temp.next.next; + size--; + } + temp = temp.next; + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + int headVal = (int)head.data; + int tailVal = (int)tail.data; + //if all the values in linkedList fall into the range, clean up; + if(min<=headVal && max>=tailVal) + { + System.out.println("min<=headVal && max>=tailVal"); + head = null; + tail = null; + size = 0; + }else{ + Node preRange = null; + Node sufRange = null; + Node temp = head; + int counter = 0; + while(temp!=null){ + if((int)temp.data=min) + { + preRange = temp; + System.out.println("Found preRange node, val="+temp.data+",next val="+temp.next.data); + } + if((int)temp.data>max){ + sufRange = temp; + System.out.println("Found sufRange node, val="+temp.data+",next val="+(temp.hasNext()?temp.next.data:null)); + break; + } + if((int)temp.data>=min && (int)temp.data<=max) + { + counter++; + } + System.out.println("Counter="+counter); + temp = temp.next; + } + if(min<=headVal){ + head = sufRange; + } + if(max>=tailVal){ + tail = preRange; + } + if(preRange!=null){ + preRange.next = sufRange; + } + size -= counter; + } + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + if(size==0 || list==null || list.size()==0) + { + return new LinkedList(); + }else{ + int pos1=0; + int pos2=0; + LinkedList result = new LinkedList(); + while(pos1val2) + { + if(pos2 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/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/Connection.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/Connection.java new file mode 100644 index 0000000000..98046b6c8f --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/Connection.java @@ -0,0 +1,23 @@ +package org.pan.coding2017.multThreadDownload.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/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionException.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionException.java new file mode 100644 index 0000000000..cb3a1b6d0a --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionException.java @@ -0,0 +1,7 @@ +package org.pan.coding2017.multThreadDownload.api; + +public class ConnectionException extends Exception { + public ConnectionException(Exception e){ + super(e); + } +} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionManager.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionManager.java new file mode 100644 index 0000000000..4ac353f33d --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package org.pan.coding2017.multThreadDownload.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/DownloadListener.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/DownloadListener.java new file mode 100644 index 0000000000..0de8c742d0 --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/DownloadListener.java @@ -0,0 +1,5 @@ +package org.pan.coding2017.multThreadDownload.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionImpl.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionImpl.java new file mode 100644 index 0000000000..d8639a5b6b --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionImpl.java @@ -0,0 +1,67 @@ +package org.pan.coding2017.multThreadDownload.api.impl; + +import org.pan.coding2017.multThreadDownload.api.Connection; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; + + +public class ConnectionImpl implements Connection { + + private URL url; + private static final int BUFFER_SIZE = 1024; + + ConnectionImpl(){} + + ConnectionImpl(String url) throws MalformedURLException { + this.url = new URL(url); + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); + urlConnection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + InputStream inputStream = urlConnection.getInputStream(); + + byte[] buff = new byte[BUFFER_SIZE]; + int totalSize = endPos - startPos + 1; + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + while (byteArrayOutputStream.size() < totalSize) { + int readSize = inputStream.read(buff); + if (readSize < 0) { + break; + } + byteArrayOutputStream.write(buff, 0, readSize); + } + byte[] data = byteArrayOutputStream.toByteArray(); + if (byteArrayOutputStream.size() > totalSize) { + return Arrays.copyOf(data, totalSize); + } + return data; + } + + @Override + public int getContentLength() { + URLConnection con; + try { + con = url.openConnection(); + return con.getContentLength(); + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } + + @Override + public void close() { + + } + +} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionManagerImpl.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..5a555652fc --- /dev/null +++ b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/multThreadDownload/api/impl/ConnectionManagerImpl.java @@ -0,0 +1,23 @@ +package org.pan.coding2017.multThreadDownload.api.impl; + + +import org.pan.coding2017.multThreadDownload.api.Connection; +import org.pan.coding2017.multThreadDownload.api.ConnectionManager; + +import java.io.IOException; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) { + try { + ConnectionImpl conn=null; + conn=new ConnectionImpl(url); + return conn; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/Dom4JUtil.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/Dom4JUtil.java deleted file mode 100644 index f1679f6bef..0000000000 --- a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/Dom4JUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.pan.coding2017.utils; - -import java.io.FileWriter; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; - -public class Dom4JUtil { - - public static Document getDocument(String xmlPath) { - - try { - //创建解析器 - SAXReader saxReader = new SAXReader(); - //得到Documment - Document document = saxReader.read(xmlPath); - return document; - } catch (DocumentException e) { - e.printStackTrace(); - } - - return null; - } - - public static void xmlWrite(Document document,String xmlPath){ - - try { - OutputFormat format = OutputFormat.createPrettyPrint(); - XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlPath),format); - xmlWriter.write(document); - xmlWriter.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - - } - -} diff --git a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/JaxpSAXPUtil.java b/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/JaxpSAXPUtil.java deleted file mode 100644 index 8756c8ab95..0000000000 --- a/group11/252308879/dataStructure/src/main/java/org/pan/coding2017/utils/JaxpSAXPUtil.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.pan.coding2017.utils; - -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -public class JaxpSAXPUtil { - public static void main(String[] args) { - /* - * 1、创建解析器工厂 - * 2、创建解析器 - * 3、执行 parse 方法 - * - * 4、自己创建一个类、继承DefaultHandler - * 5、重写类里面的三个方法 - */ - - try { - SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); - SAXParser saxParser = saxParserFactory.newSAXParser(); - saxParser.parse("src/p1.xml",new MyDeafultHandler2() ); - } catch (Exception e) { - e.printStackTrace(); - } - - - } - -} - -class MyDeafultHandler1 extends DefaultHandler{ - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - System.out.println("<"+qName+">"); - } - - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - System.out.println(new String(ch,start,length)); - } - - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - System.out.println("<"+qName+"/>"); - } - -} - -//实现获取所有的name元素的值 -class MyDeafultHandler2 extends DefaultHandler{ - - boolean flag = false; - int index = 1; - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - //判断qName 是否为 name 元素 - if("name".equals(qName) && index == 2){ - flag = true; - } - } - - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - if(flag == true){ - System.out.println(new String(ch, start, length)); - } - } - - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - if("name".equals(qName)){ - flag = false; - index++ ; - } - } - - -} diff --git a/group11/252308879/dataStructure/src/test/java/org/pan/coding2017/basic/LinkedListTest.java b/group11/252308879/dataStructure/src/test/java/org/pan/coding2017/basic/LinkedListTest.java index d10e2a1d48..135e052218 100644 --- a/group11/252308879/dataStructure/src/test/java/org/pan/coding2017/basic/LinkedListTest.java +++ b/group11/252308879/dataStructure/src/test/java/org/pan/coding2017/basic/LinkedListTest.java @@ -8,11 +8,11 @@ */ public class LinkedListTest { - LinkedList linkedList; + org.pan.coding2017.basic2.LinkedList linkedList; @Before public void setUp() throws Exception { - linkedList = new LinkedList(); + linkedList = new org.pan.coding2017.basic2.LinkedList(); linkedList.add(0); linkedList.add(1); linkedList.add(2); diff --git a/group11/395443277/src/com/coderising/download/DownloadThread.java b/group11/395443277/src/com/coderising/download/DownloadThread.java index 8428d2ada8..79be3a0c52 100644 --- a/group11/395443277/src/com/coderising/download/DownloadThread.java +++ b/group11/395443277/src/com/coderising/download/DownloadThread.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.io.RandomAccessFile; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; import com.coderising.download.api.Connection; @@ -10,25 +12,35 @@ public class DownloadThread extends Thread { int startPos; int endPos; String filePath; + CyclicBarrier barrier; - public DownloadThread(Connection conn, int startPos, int endPos, String filePath) { + public DownloadThread(Connection conn, int startPos, int endPos, String filePath, CyclicBarrier barrier) { this.conn = conn; this.startPos = startPos; this.endPos = endPos; this.filePath = filePath; + this.barrier = barrier; } public void run() { try { - synchronized (filePath.getClass()) { - byte[] bytes = conn.read(startPos, endPos); - RandomAccessFile RAFile = new RandomAccessFile(filePath, "rw"); - RAFile.seek(startPos); - RAFile.write(bytes, 0, bytes.length); - RAFile.close(); - } + byte[] bytes = conn.read(startPos, endPos); + System.out.println(bytes.length); + + RandomAccessFile RAFile = new RandomAccessFile(filePath, "rw"); + RAFile.seek(startPos); + RAFile.write(bytes, 0, bytes.length); + RAFile.close(); + conn.close(); + + barrier.await(); } catch (IOException e) { + // TODO: what if download fail, deal with exception, need to inform main thread. + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { e.printStackTrace(); } } diff --git a/group11/395443277/src/com/coderising/download/FileDownloader.java b/group11/395443277/src/com/coderising/download/FileDownloader.java index 7cd70f4b81..6d221f8c28 100644 --- a/group11/395443277/src/com/coderising/download/FileDownloader.java +++ b/group11/395443277/src/com/coderising/download/FileDownloader.java @@ -1,7 +1,8 @@ package com.coderising.download; -import java.io.File; +import java.io.IOException; import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; import com.coderising.download.api.Connection; import com.coderising.download.api.ConnectionException; @@ -20,7 +21,7 @@ public FileDownloader(String _url) { this.url = _url; } - public void execute() { + public void execute(String filePath) { // 在这里实现你的代码, 注意: 需要用多线程实现下载 // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, @@ -39,35 +40,36 @@ public void execute() { Connection conn = null; try { + final int NUM_THREADS = 3; + conn = cm.open(this.url); int length = conn.getContentLength(); + System.out.println("total file size is: " + length); // Separate length to 3 - int partLen = (int) Math.ceil(length / 3); + int partLen = (int) Math.ceil(length / NUM_THREADS); // create a file - String filePath = "D://java_learning//test.jpg"; - - // create three threads -// DownloadThread t1 = new DownloadThread(cm.open(this.url), 0, partLen - 1, filePath); -// t1.start(); -// t1.join(); -// -// DownloadThread t2 = new DownloadThread(cm.open(this.url), partLen, partLen * 2 - 1, filePath); -// t2.start(); -// t2.join(); -// -// DownloadThread t3 =new DownloadThread(cm.open(this.url), partLen * 2, length - 1, filePath); -// t3.start(); -// t3.join(); - - new DownloadThread(cm.open(this.url), 0, length-1, filePath).start(); - -// getListener().notifyFinished(); - + createPlaceHolderFile(filePath, length); + + Runnable barrierAction = new Runnable() { + @Override + public void run() { + getListener().notifyFinished(); + } + }; + + CyclicBarrier barrier = new CyclicBarrier(3, barrierAction); + + new DownloadThread(cm.open(this.url), 0, partLen - 1, filePath, barrier).start(); + new DownloadThread(cm.open(this.url), partLen, partLen * 2 - 1, filePath, barrier).start(); + new DownloadThread(cm.open(this.url), partLen * 2, length - 1, filePath, barrier).start(); + } catch (ConnectionException e) { e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); } finally { if (conn != null) { conn.close(); @@ -76,6 +78,16 @@ public void execute() { } + private void createPlaceHolderFile(String filePath, int contentLength) throws IOException { + RandomAccessFile file = new RandomAccessFile(filePath, "rw"); + + for (int i = 0; i < contentLength; i++) { + file.write(0); + } + + file.close(); + } + public void setListener(DownloadListener listener) { this.listener = listener; } diff --git a/group11/395443277/src/com/coderising/download/FileDownloaderTest.java b/group11/395443277/src/com/coderising/download/FileDownloaderTest.java index 7e4d8d789d..152edbc664 100644 --- a/group11/395443277/src/com/coderising/download/FileDownloaderTest.java +++ b/group11/395443277/src/com/coderising/download/FileDownloaderTest.java @@ -23,7 +23,7 @@ public void testDownload() { // String url = "https://s-media-cache-ak0.pinimg.com/564x/8e/bd/00/8ebd00b1f2ef862b6c80d57c2b45d129.jpg"; // http://wallpapercraze.com/images/wallpapers/dota2_nevermore_w1.jpeg - String url = "https://i.ytimg.com/vi/xMV2s5f3f0E/hqdefault.jpg"; + String url = "http://eskipaper.com/images/large-2.jpg"; FileDownloader downloader = new FileDownloader(url); @@ -39,8 +39,8 @@ public void notifyFinished() { }); - - downloader.execute(); + String filePath = "D://java_learning//test.jpg"; + downloader.execute(filePath); // 等待多线程下载程序执行完毕 while (!downloadFinished) { diff --git a/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java b/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java index cde4246282..c1de2c97b9 100644 --- a/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java +++ b/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java @@ -1,20 +1,23 @@ package com.coderising.download.impl; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.util.Arrays; + import com.coderising.download.api.Connection; public class ConnectionImpl implements Connection { HttpURLConnection urlcon = null; - InputStream is; + static final int BUFFER_SIZE = 1024; public ConnectionImpl(String url) { try { URL imgUrl = new URL(url); urlcon = (HttpURLConnection) imgUrl.openConnection(); - is = urlcon.getInputStream(); } catch (Exception e) { System.out.println(e); } @@ -22,16 +25,30 @@ public ConnectionImpl(String url) { @Override public byte[] read(int startPos, int endPos) throws IOException { - byte[] bytes = new byte[endPos - startPos + 1]; + urlcon.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + + InputStream is = urlcon.getInputStream(); + + byte[] buff = new byte[BUFFER_SIZE]; + + int totalLength = endPos - startPos + 1; + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // Read in the bytes - int offset = startPos; - int numRead = 0; - while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { - offset += numRead; + while (baos.size() < totalLength) { + int len = is.read(buff); + if (len < 0) { + break; + } + baos.write(buff, 0, len); } - return bytes; + if (baos.size() > totalLength) { + byte[] data = baos.toByteArray(); + return Arrays.copyOf(data, totalLength); + } + + return baos.toByteArray(); } @Override @@ -47,12 +64,12 @@ public int getContentLength() { @Override public void close() { - try { - is.close(); - System.out.println("one connection is closed"); - } catch (IOException e) { - e.printStackTrace(); - } + // try { + // is.close(); + // System.out.println("one connection is closed"); + // } catch (IOException e) { + // e.printStackTrace(); + // } } } diff --git a/group11/395443277/src/com/coding/basic/ArrayList.java b/group11/395443277/src/com/coding/basic/ArrayList.java index 93a2781f3b..46e9eae20c 100644 --- a/group11/395443277/src/com/coding/basic/ArrayList.java +++ b/group11/395443277/src/com/coding/basic/ArrayList.java @@ -3,67 +3,77 @@ import java.util.Arrays; public class ArrayList implements List { - + private int size = 0; - + private Object[] elementData = new Object[4]; - - public void add(Object o){ - if (size == elementData.length) { - // double size - doubleSize(); - } - + + public void add(Object o) { + ensureCapacity(size + 1); elementData[size] = o; size++; } - - private void doubleSize() { - 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[] newArray = new Object[newCapacity]; + System.arraycopy(elementData, 0, newArray, 0, elementData.length); + elementData = newArray; + } } - - public void add(int index, Object o){ - // check size - if (size == elementData.length) { - doubleSize(); + + public void add(int index, Object o) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); } - - //shift and add element - System.arraycopy(elementData, index, elementData, index+1, size - index); + + ensureCapacity(size + 1); + // shift and add element + System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = o; size++; } - - public Object get(int index){ + + public Object get(int index) { + // check input + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + return elementData[index]; } - - public Object remove(int index){ + + public Object remove(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + if (size == 0) { return null; } - + // remove element and shift Object target = elementData[index]; - System.arraycopy(elementData, index+1, elementData, index, size - index - 1); - + System.arraycopy(elementData, index + 1, elementData, index, size - index - 1); + // reset last element - elementData[size-1] = null; + elementData[size - 1] = null; size--; return target; } - - public int size(){ + + public int size() { return size; } - - public Iterator iterator (){ + + public Iterator iterator() { return new SeqIterator(); } - + private class SeqIterator implements Iterator { int i = 0; - + @Override public boolean hasNext() { return i < size; @@ -76,7 +86,7 @@ public Object next() { } return elementData[i++]; } - + } - + } diff --git a/group11/395443277/src/com/coding/basic/ArrayListTest.java b/group11/395443277/src/com/coding/basic/ArrayListTest.java index 75bae320f4..ec99bc24f6 100644 --- a/group11/395443277/src/com/coding/basic/ArrayListTest.java +++ b/group11/395443277/src/com/coding/basic/ArrayListTest.java @@ -58,7 +58,6 @@ public void testRemove() { assertEquals(2, list.get(2)); assertEquals(4, list.size()); - assertEquals(null, list.get(4)); list.add(6); assertEquals(6, list.get(4)); diff --git a/group11/395443277/src/com/coding/basic/BinaryTreeNode.java b/group11/395443277/src/com/coding/basic/BinaryTreeNode.java index 907fc23275..7ebd1f2a4e 100644 --- a/group11/395443277/src/com/coding/basic/BinaryTreeNode.java +++ b/group11/395443277/src/com/coding/basic/BinaryTreeNode.java @@ -1,37 +1,49 @@ package com.coding.basic; -public class BinaryTreeNode implements Comparable{ - +public class BinaryTreeNode implements Comparable { + 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){ - if (this.compareTo(o)==0) { - return null; + + public BinaryTreeNode insert(Object o) { + // root element + if (this.data == null) { + this.data = o; + return this; + } + + // equals return the node + if (this.compareTo(o) == 0) { + return this; } else { // current value less than inserted value // go right - if (this.compareTo(o)<0) { + if (this.compareTo(o) < 0) { if (this.right == null) { BinaryTreeNode nd = new BinaryTreeNode(); nd.setData(o); @@ -39,10 +51,10 @@ public BinaryTreeNode insert(Object o){ } else { this.getRight().insert(o); } - } + } // greater than // go left - else if(this.compareTo(o)>0) { + else if (this.compareTo(o) > 0) { if (this.left == null) { BinaryTreeNode nd = new BinaryTreeNode(); nd.setData(o); @@ -52,24 +64,24 @@ else if(this.compareTo(o)>0) { } } } - - return null; + + return null; } - + /** * oversimplified implementation: only allows int and string */ @Override - public int compareTo(Object nd) throws ClassCastException{ + public int compareTo(Object nd) throws ClassCastException { if (!(nd instanceof Object)) { throw new ClassCastException("An object expected."); } - + if (nd instanceof String) { - return ((String)this.data).compareTo((String) nd); + return ((String) this.data).compareTo((String) nd); } else { - return ((int) this.data) -((int) nd); + return ((int) this.data) - ((int) nd); } } - + } diff --git a/group11/395443277/src/com/coding/basic/Queue.java b/group11/395443277/src/com/coding/basic/Queue.java index f12e73d46d..4b29108ef9 100644 --- a/group11/395443277/src/com/coding/basic/Queue.java +++ b/group11/395443277/src/com/coding/basic/Queue.java @@ -2,20 +2,24 @@ public class Queue { private LinkedList elementData = new LinkedList(); - - public void enQueue(Object o){ + + public void enQueue(Object o) { elementData.add(o); } - - public Object deQueue(){ + + public Object deQueue() { + if (size() == 0) { + return null; + } + return elementData.removeFirst(); } - - public boolean isEmpty(){ - return elementData.size()==0; + + public boolean isEmpty() { + return elementData.size() == 0; } - - public int size(){ + + public int size() { return elementData.size(); } } 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/liuxin/src/com/coderising/download/api/ConnectionManager.java b/group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionManager.java similarity index 100% rename from liuxin/src/com/coderising/download/api/ConnectionManager.java rename to group12/2258659044/zj-2017/src/com/coderising/download/api/ConnectionManager.java 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/liuxin/src/com/coderising/litestruts/struts.xml b/group12/2258659044/zj-2017/src/com/coderising/litestruts/struts.xml similarity index 100% rename from liuxin/src/com/coderising/litestruts/struts.xml rename to group12/2258659044/zj-2017/src/com/coderising/litestruts/struts.xml 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/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/StrutsTest.java b/group12/282742732/learning_1/src/com/coderising/litestruts/StrutsTest.java similarity index 100% rename from group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/StrutsTest.java rename to group12/282742732/learning_1/src/com/coderising/litestruts/StrutsTest.java diff --git a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/View.java b/group12/282742732/learning_1/src/com/coderising/litestruts/View.java similarity index 100% rename from group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/View.java rename to group12/282742732/learning_1/src/com/coderising/litestruts/View.java diff --git a/group11/1178243325/DataStructure/src/main/resources/struts.xml b/group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml similarity index 80% rename from group11/1178243325/DataStructure/src/main/resources/struts.xml rename to group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml index ae0ce37fd8..a4ca47c733 100644 --- a/group11/1178243325/DataStructure/src/main/resources/struts.xml +++ b/group12/282742732/learning_1/src/com/coderising/litestruts/struts.xml @@ -1,6 +1,6 @@ - + /jsp/homepage.jsp /jsp/showLogin.jsp @@ -8,4 +8,4 @@ /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/group24/330657387/src/com/coding/basic/BinaryTreeNode.java b/group12/282742732/learning_1/src/com/coding/basic/BinaryTreeNode.java similarity index 100% rename from group24/330657387/src/com/coding/basic/BinaryTreeNode.java rename to group12/282742732/learning_1/src/com/coding/basic/BinaryTreeNode.java diff --git a/group24/330657387/src/com/coding/basic/Iterator.java b/group12/282742732/learning_1/src/com/coding/basic/Iterator.java similarity index 100% rename from group24/330657387/src/com/coding/basic/Iterator.java rename to group12/282742732/learning_1/src/com/coding/basic/Iterator.java 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/group24/330657387/src/com/coding/basic/List.java b/group12/282742732/learning_1/src/com/coding/basic/List.java similarity index 100% rename from group24/330657387/src/com/coding/basic/List.java rename to group12/282742732/learning_1/src/com/coding/basic/List.java diff --git a/group12/495473393/Coding/src/Base/Queue.java b/group12/282742732/learning_1/src/com/coding/basic/Queue.java similarity index 55% rename from group12/495473393/Coding/src/Base/Queue.java rename to group12/282742732/learning_1/src/com/coding/basic/Queue.java index 9c2948d7e3..d16a441644 100644 --- a/group12/495473393/Coding/src/Base/Queue.java +++ b/group12/282742732/learning_1/src/com/coding/basic/Queue.java @@ -1,11 +1,14 @@ -package Base; +package com.coding.basic; public class Queue { - public void enQueue(Object o){ + LinkedList elementData = new LinkedList(); + public void enQueue(Object o){ + elementData.add(o); } public Object deQueue(){ + return null; } 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/group12/377401843/learning_1/src/com/guodong/datastructure/Iterator.java b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java similarity index 70% rename from group12/377401843/learning_1/src/com/guodong/datastructure/Iterator.java rename to group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java index 8d486220b0..0d9e6013d6 100644 --- a/group12/377401843/learning_1/src/com/guodong/datastructure/Iterator.java +++ b/group12/377401843/learning/src/main/java/com/zhaogd/collection/Iterator.java @@ -1,7 +1,9 @@ -package com.guodong.datastructure; +package com.zhaogd.collection; public interface Iterator { + public boolean hasNext(); + public Object next(); } 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/liuxin/src/com/coderising/download/api/DownloadListener.java b/group12/382266293/src/com/coderising/download/api/DownloadListener.java similarity index 100% rename from liuxin/src/com/coderising/download/api/DownloadListener.java rename to group12/382266293/src/com/coderising/download/api/DownloadListener.java 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/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/struts.xml b/group12/382266293/src/litestruts/struts.xml similarity index 95% rename from group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/struts.xml rename to group12/382266293/src/litestruts/struts.xml index ae0ce37fd8..fb0c2be3de 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coderising/litestruts/struts.xml +++ b/group12/382266293/src/litestruts/struts.xml @@ -8,4 +8,4 @@ /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/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java b/group12/563253496/week2/src/litestruts/LoginAction.java similarity index 96% rename from group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java rename to group12/563253496/week2/src/litestruts/LoginAction.java index 5496d8084d..bba4c11c9f 100644 --- a/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java +++ b/group12/563253496/week2/src/litestruts/LoginAction.java @@ -1,4 +1,4 @@ -package com.coderising.action; +package litestruts; /** * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 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/group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java b/group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java similarity index 95% rename from group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java rename to group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java index 683868be1d..d7ac820192 100644 --- a/group13/1274639949/lesson01/src/com/hans/BinaryTreeNode.java +++ b/group12/563253496/week3/src/com/coding/basic/BinaryTreeNode.java @@ -1,4 +1,4 @@ -package com.hans; +package com.coding.basic; public class BinaryTreeNode { 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/group24/330657387/src/com/coding/basic/Queue.java b/group12/563253496/week3/src/com/coding/basic/Queue.java similarity index 100% rename from group24/330657387/src/com/coding/basic/Queue.java rename to group12/563253496/week3/src/com/coding/basic/Queue.java diff --git a/group24/330657387/src/com/coding/basic/Stack.java b/group12/563253496/week3/src/com/coding/basic/Stack.java similarity index 100% rename from group24/330657387/src/com/coding/basic/Stack.java rename to group12/563253496/week3/src/com/coding/basic/Stack.java 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= size) { - throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); - } - } - - private void checkForAdd(int index) { - if (index < 0 || index > size) { - throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); - } - } - - private static class Node { - Object data; - Node next; - - public Node() { - } - - public Node(Object data, Node next) { - this.data = data; - this.next = next; - } - } - - private class LinkedListIterator implements Iterator{ - - private Node next; - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - public Object next() { - if (next == null) { - throw new IndexOutOfBoundsException("there is no node in list"); - } - Node ret = next; - next = next.next; - return ret.data; - } - } -} +package com.coding.basic; + +public class LinkedList implements List { + + private Node head; + private int size = 0; + private Iterator iterator = new LinkedListIterator(); + + + public void add(Object o) { + Node newNode = new Node(o, null); + if (head == null) { + head = newNode; + } else { + node(size - 1).next = newNode; + } + size++; + } + + public void add(int index, Object o) { + checkForAdd(index); + if (index == size) { + add(o); + } else { + Node newNode = new Node(o, null); + if (index == 0) { + addFirst(o); + } else { + Node preNode = node(index - 1); + Node now = preNode.next; + preNode.next = newNode; + newNode.next = now; + size++; + } + } + + } + + private Node node(int index) { + Node x = head; + for (int i = 0; i < index; i++) { + x = x.next; + } + return x; + } + + public Object get(int index) { + checkIndex(index); + return node(index).data; + } + + /** + * 让被删除的引用的持有者指向下一个节点 + * + * @param index + * @return + */ + public Object remove(int index) { + final Object ret; + checkIndex(index); + if (index == 0) { + Node removeNode = head; + ret = head.data; + head = removeNode.next; + } else { + Node pre = node(index - 1); + Node removeNode = pre.next; + ret = removeNode.data; + pre.next = removeNode.next; + } + size--; + return ret; + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + head = new Node(o, head); + ; + size++; + } + + public void addLast(Object o) { + add(o); + } + + public Object removeFirst() { + if (size == 0) { + return null; + } else { + return remove(0); + } + } + + public Object removeLast() { + return remove(size - 1); + } + + public Iterator iterator() { + return iterator; + } + + private void checkIndex(int index) { + if (index < 0 || index >= size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + private void checkForAdd(int index) { + if (index < 0 || index > size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + if (size == 0) { + return; + } + Node[] nodes = new Node[size]; + int i = 0; + // 迭代链表的数据生成数组 + while (iterator.hasNext()) { + nodes[i++] = (Node) iterator.next(); + } + // 遍历数组越生成新的 链表 + Node newHead = nodes[--i]; + Node next = newHead.next; + for (int j = --i; j >= 0; j--) { + next.next = nodes[j]; + next = next.next; + + } + this.head = newHead; + + } + + /** + * 删除一个单链表的前半部分 + * 例如: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; + } + + private static class Node { + Object data; + Node next; + + public Node() { + } + + public Node(Object data, Node next) { + this.data = data; + this.next = next; + } + } + + private class LinkedListIterator implements Iterator { + + private Node next; + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public Object next() { + if (next == null) { + throw new IndexOutOfBoundsException("there is no node in list"); + } + Node ret = next; + next = next.next; + return ret.data; + } + } +} diff --git a/group17/1204187480/code/homework/basic/src/test/java/com/coding/basic/LinkedListTest.java b/group17/1204187480/code/homework/basic/src/test/java/com/coding/basic/LinkedListTest.java new file mode 100644 index 0000000000..06efea8aa0 --- /dev/null +++ b/group17/1204187480/code/homework/basic/src/test/java/com/coding/basic/LinkedListTest.java @@ -0,0 +1,27 @@ +package com.coding.basic; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by luoziyihao on 3/23/17. + */ +public class LinkedListTest { + @Test + public void iterator() throws Exception { + + } + + @Test + public void reverse() throws Exception { + LinkedList linkedList = new LinkedList(); + linkedList.add("1"); + linkedList.add("2"); + linkedList.add("3"); + linkedList.add("4"); + linkedList.reverse(); + System.out.println(linkedList); + } + +} \ No newline at end of file diff --git a/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/action/LoginAction.java b/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/action/LoginAction.java new file mode 100644 index 0000000000..85ae4dc47c --- /dev/null +++ b/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/action/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts.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; + } +} diff --git a/group17/1204187480/code/homework/coderising/src/main/resources/struts.xml b/group17/1204187480/code/homework/coderising/src/main/resources/struts.xml index dd598a3664..c7ee86e436 100644 --- a/group17/1204187480/code/homework/coderising/src/main/resources/struts.xml +++ b/group17/1204187480/code/homework/coderising/src/main/resources/struts.xml @@ -1,10 +1,10 @@ - + /jsp/homepage.jsp /jsp/showLogin.jsp - + /jsp/welcome.jsp /jsp/error.jsp diff --git a/group17/240094626/work_0305/src/com/coderising/download/DownloadThread.java b/group17/240094626/work_0305/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..7cb544ba0c --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,51 @@ +package com.coderising.download; + +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + private Connection conn; + private int startPos; + private int endPos; + private int threadId; + private String localFile; + private static final int BUFF_LENGTH = 1024 * 4; + boolean isFinished = false; + int currSize = 0; + CyclicBarrier barrier; + + public DownloadThread( Connection conn, int startPos, int endPos,int threadId,String localFile,CyclicBarrier barrier){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.threadId = threadId; + this.localFile = localFile; + this.barrier = barrier; + } + public void run(){ + try { + System.out.println("Thread"+threadId+" begin download bytes range:"+startPos+"-"+endPos); + RandomAccessFile raf = new RandomAccessFile(localFile, "rw"); + int totalLen = endPos - startPos + 1; + while(currSize < totalLen){ + int start = currSize + startPos; + int end = start + BUFF_LENGTH-1; + byte[] data = conn.read(start,(end>endPos?endPos:end)); + + raf.seek(start); + raf.write(data); + currSize += data.length; + + + } + raf.close(); + barrier.await(); //等待别的线程完成 + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/group17/240094626/work_0305/src/com/coderising/download/FileDownloader.java b/group17/240094626/work_0305/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..2081831155 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,125 @@ +package com.coderising.download; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + private String url; + + private DownloadListener listener; + + private ConnectionManager cm; + + private String localFile; + + private int threadNum; + + //一组开始下载位置 + private int[] startPos; + //一组结束下载位置 + private int[] endPos; + + + public FileDownloader(String _url,int threadNum,String localFile) { + this.url = _url; + this.threadNum = threadNum; + this.localFile = localFile; + startPos = new int[threadNum]; + endPos = new int[threadNum]; + + } + + 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方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + + CyclicBarrier barrier = new CyclicBarrier(threadNum, new Runnable() { + @Override + public void run() { + listener.notifyFinished(); + } + }); + + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + if(length > 0){ + holderFile(localFile,length); + + for(int i = 0 , len = length/threadNum; i < threadNum; i++){ + int size = i * len; + startPos[i] = size; + if(i == threadNum-1){ + endPos[i] = length - 1; + }else{ + endPos[i] = size + len-1; + } + new DownloadThread(cm.open(url), + startPos[i], + endPos[i], + i+1, + localFile, + barrier).start(); + } + + } + + + } catch (Exception e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + private void holderFile(String localFile, int length) throws IOException { + RandomAccessFile raf = new RandomAccessFile(localFile, "rw"); + for(int i = 0; i < length; i++){ + raf.write(0); + } + raf.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/group17/240094626/work_0305/src/com/coderising/download/FileDownloaderTest.java b/group17/240094626/work_0305/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..57499dd4b7 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,60 @@ +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://images2015.cnblogs.com/blog/610238/201604/610238-20160421154632101-286208268.png"; + String localFile = "E:\\Users\\2017coding\\temp\\pic.png"; + int threadNum = Runtime.getRuntime().availableProcessors(); + FileDownloader downloader = new FileDownloader(url,threadNum,localFile); + + + 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/group17/240094626/work_0305/src/com/coderising/download/api/Connection.java b/group17/240094626/work_0305/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..41d308f445 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/api/Connection.java @@ -0,0 +1,24 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + * @throws Exception + */ + public byte[] read(int startPos,int endPos) throws Exception; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group17/240094626/work_0305/src/com/coderising/download/api/ConnectionException.java b/group17/240094626/work_0305/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..93dbe37805 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,58 @@ +package com.coderising.download.api; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; + +public class ConnectionException extends Exception { + + private static final long serialVersionUID = 5581807994119179835L; + private String message; + private Throwable t; + private String stackTrace; + + public Throwable getCause(){ + return this.t; + } + + public String toString(){ + return this.message; + } + + public void printStackTrace() { + System.err.print(this.stackTrace); + } + + public void printStackTrace(PrintStream paramPrintStream) { + printStackTrace(new PrintWriter(paramPrintStream)); + } + + public void printStackTrace(PrintWriter paramPrintWriter) { + paramPrintWriter.print(this.stackTrace); + } + + public ConnectionException(String paramString) { + super(paramString); + this.message = paramString; + this.stackTrace = paramString; + } + + public ConnectionException(Throwable paramThrowable) { + super(paramThrowable.getMessage()); + this.t = paramThrowable; + StringWriter localStringWriter = new StringWriter(); + paramThrowable.printStackTrace(new PrintWriter(localStringWriter)); + this.stackTrace = localStringWriter.toString(); + } + + public ConnectionException(String paramString, Throwable paramThrowable) { + super(paramString + "; nested exception is " + + paramThrowable.getMessage()); + this.t = paramThrowable; + this.message = paramString; + StringWriter localStringWriter = new StringWriter(); + paramThrowable.printStackTrace(new PrintWriter(localStringWriter)); + this.stackTrace = localStringWriter.toString(); + } + +} diff --git a/group17/240094626/work_0305/src/com/coderising/download/api/ConnectionManager.java b/group17/240094626/work_0305/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/group17/240094626/work_0305/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/group17/240094626/work_0305/src/com/coderising/download/api/DownloadListener.java b/group17/240094626/work_0305/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/group17/240094626/work_0305/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/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionImpl.java b/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..0692bc6dfb --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,67 @@ +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.coderising.download.api.ConnectionException; + +class ConnectionImpl implements Connection{ + + private static final int BUFF_SIZE = 1024; + + private URL url; + + ConnectionImpl(String _url) throws ConnectionException{ + try { + this.url = new URL(_url); + } catch (MalformedURLException e) { + throw new ConnectionException(e); + } + } + + @Override + public byte[] read(int startPos, int endPos) throws Exception { + if(startPos > endPos){ + throw new IllegalArgumentException("startPos:"+startPos+",endPos:"+endPos); + } + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + String property = "bytes="+startPos+"-"+endPos; + conn.setRequestProperty("RANGE", property); + conn.connect(); + int totalLen = endPos - startPos + 1; + InputStream is = conn.getInputStream(); + byte[] bytes = new byte[totalLen]; + byte[] buff = new byte[BUFF_SIZE]; + int len, + count = 0; + while((len = is.read(buff) ) > 0 && count < totalLen){ + + System.arraycopy(buff, 0, bytes,count, len); + count += len; + } + return bytes; + } + + @Override + public int getContentLength() { + HttpURLConnection conn; + try { + conn = (HttpURLConnection) url.openConnection(); + return conn.getContentLength(); + } catch (IOException e) { + e.printStackTrace(); + } + + return -1; + } + + @Override + public void close() { + + } + +} diff --git a/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..c7d47979c8 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,14 @@ +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/group17/240094626/work_0305/src/com/coderising/linkedlist/Iterator.java b/group17/240094626/work_0305/src/com/coderising/linkedlist/Iterator.java new file mode 100644 index 0000000000..30ea750ecc --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/linkedlist/Iterator.java @@ -0,0 +1,8 @@ +package com.coderising.linkedlist; + +public interface Iterator { + + public boolean hasNext(); + + public E next(); +} diff --git a/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedList.java b/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedList.java new file mode 100644 index 0000000000..feddaedd23 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedList.java @@ -0,0 +1,293 @@ +package com.coderising.linkedlist; + +import java.util.HashMap; +import java.util.Map; + +public class LinkedList implements List { + + transient Node head; + transient int size; + + public LinkedList(){ + head = new Node(null,head); + size = 0; + } + public void addFirst(E e){ + head.next = new Node(e,head.next); + size++; + } + + + public void addAfter(Node n, E e){ + if(n == head){ + addFirst(e); + }else{ + Node curr = new Node(e,n.next); + n.next = curr; + size++; + } + } + + + private void checkRange(int index){ + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size); + } + } + + private Node getNode(int index){ + checkRange(index); + Node curr = head; + for(; index >= 0 ; index--){ + curr = curr.next; + } + return curr; + } + + public void add(E e) { + add(size,e); + } + + public void add(int index, E e) { + if(index < 0 || index > size){ + throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size); + } + if(index == 0){ + addFirst(e); + }else{ + addAfter(getNode(index-1), e); + } + } + + public E get(int index) { + Node n = getNode(index); + return n.e; + } + + + public E remove(int index) { + checkRange(index); + Node preN = null, + currN = null; + if(index == 0){ + preN = head; + }else{ + preN = getNode(index-1); + } + currN = preN.next; + preN.next = currN.next; + E e = currN.e; + currN.e = null; + currN.next = null; + size--; + return e; + + } + + public int size() { + return size; + } + + + private static class Node{ + E e ; + Node next; + + public Node(E e,Node next){ + this.e = e; + this.next = next; + } + } + + private Iterator iterator(){ + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator{ + + int index; + public LinkedListIterator(){ + index = 0; + } + + @Override + public boolean hasNext() { + if(index < size){ + return true; + } + return false; + } + + @Override + public E next() { + Node curr = (Node) getNode(index++); + return curr.e; + } + + } + + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if(size > 1){ + int index = 0; + Node a = null, + preA = null, + b = null, + preB = null; + for(;index < size/2; index++){ + if(index == 0){ + preA = head; + a = head.next; + b = getNode(size-1); + preB = getNode(size-2); + + head.next = b; + preB.next = a; + b.next = a.next; + a.next = head; + }else{ + preA = getNode(index-1); + a = preA.next; + preB = getNode(size-2-index); + b = preB.next; + + preA.next = b; + preB.next = a; + Node tmp = a.next; + a.next = b.next; + b.next = tmp; + } + + } + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + remove(0, size/2); + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + while(length > 0){ + remove(i); + 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[] a = new int[list.size]; + for(int i = 0; i < list.size; i++){ + Node curr = getNode((int)list.get(i)); + a[i] = (int) curr.e; + } + return a; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + * @param list + */ + + public void subtract(LinkedList list){ + int i = 0, + j = 0; + for(; i < list.size; i++){ + E a = (E) list.get(i); + while(j < size){ + E b = get(j); + if(a.equals(b)){ + remove(j); + break; + } + j++; + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + Map map = new HashMap(size); + for(int i = 0; i < size; ){ + if(map.get(getNode(i).e) == null){ + map.put(getNode(i).e, i); + i++; + }else{ + remove(i); + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + if(min >= max){ + return ; + } + for(int i = 0; i < size; ){ + int a = (int)get(i); + if(min < a && max > a){ + remove(i); + continue; + } + i++; + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + LinkedList c = new LinkedList(); + if(list.size == 0){ + return c; + } + Map map = new HashMap(); + for(int i = 0; i < list.size; i++){ + E a = list.get(i); + if(null == map.get(a)){ + map.put(a, true); + } + } + for(int i = 0; i < size; i++){ + E a = get(i); + if(null == map.get(a)){ + map.put(a, true); + }else if(map.get(a)){ + c.add(get(i)); + } + } + + return c; + } +} diff --git a/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedListTest.java b/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedListTest.java new file mode 100644 index 0000000000..b245851f2a --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/linkedlist/LinkedListTest.java @@ -0,0 +1,163 @@ +package com.coderising.linkedlist; + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class LinkedListTest { + LinkedList list = new LinkedList(); + @Before + public void setUp() throws Exception { + list = new LinkedList(); + } + + @After + public void tearDown() throws Exception { + list = new LinkedList(); + } + + @Test + public void testReverse() { + list.add(3); + list.add(5); + list.add(6); + list.add(7); + list.add(9); + list.add(8); + Assert.assertEquals(3, list.get(0)); + Assert.assertEquals(5, list.get(1)); + Assert.assertEquals(6, list.get(2)); + Assert.assertEquals(7, list.get(3)); + Assert.assertEquals(9, list.get(4)); + Assert.assertEquals(8, list.get(5)); + list.reverse(); + Assert.assertEquals(8, list.get(0)); + Assert.assertEquals(9, list.get(1)); + Assert.assertEquals(7, list.get(2)); + Assert.assertEquals(6, list.get(3)); + Assert.assertEquals(5, list.get(4)); + Assert.assertEquals(3, list.get(5)); + } + @Test + public void testRemove(){ + list.add(3); + list.add(5); + list.add(6); + list.add(7); + list.add(9); + list.remove(0); + Assert.assertEquals(5, list.get(0)); + list.remove(1); + Assert.assertEquals(7, list.get(1)); + } + @Test + public void testRemoveFirstHalf(){ + list.add(3); + list.add(5); + list.add(6); + list.add(7); + list.add(9); + list.add(8); + list.removeFirstHalf(); + Assert.assertEquals(7, list.get(0)); + Assert.assertEquals(9, list.get(1)); + Assert.assertEquals(8, list.get(2)); + } + + @Test + public void testGetElements(){ + list.add(301); + list.add(401); + list.add(501); + list.add(601); + list.add(701); + list.add(801); + list.add(901); + list.add(1001); + LinkedList list1 = new LinkedList(); + list1.add(0); + list1.add(2); + list1.add(4); + list1.add(6); + int[] a = list.getElements(list1); + Assert.assertEquals(301, a[0]); + Assert.assertEquals(501, a[1]); + Assert.assertEquals(701, a[2]); + Assert.assertEquals(901, a[3]); + } + @Test + public void testSubtract(){ + list.add(301); + list.add(401); + list.add(501); + list.add(601); + list.add(701); + list.add(801); + list.add(901); + list.add(1001); + LinkedList list1 = new LinkedList(); + list1.add(401); + list1.add(701); + list1.add(801); + list.subtract(list1); + Assert.assertEquals(301, list.get(0)); + Assert.assertEquals(501, list.get(1)); + Assert.assertEquals(901, list.get(3)); + } + @Test + public void testRemoveDuplicateValues(){ + list.add(301); + list.add(401); + list.add(401); + list.add(601); + list.add(601); + list.add(801); + list.add(901); + list.add(1001); + list.removeDuplicateValues(); + Assert.assertEquals(6, list.size); + } + + @Test + public void testRemoveRange(){ + list.add(301); + list.add(401); + list.add(501); + list.add(601); + list.add(801); + list.add(901); + list.removeRange(500, 600); + Assert.assertEquals(301, list.get(0)); + Assert.assertEquals(401, list.get(1)); + Assert.assertEquals(601, list.get(2)); + } + + @Test + public void testIntersection(){ + list.add(301); + list.add(401); + list.add(501); + list.add(601); + list.add(801); + list.add(901); + LinkedList list1 = new LinkedList(); + list1.add(401); + list1.add(601); + list1.add(701); + LinkedList c = list.intersection(list1); + Assert.assertEquals(401,c.get(0)); + Assert.assertEquals(601,c.get(1)); + } + public static void main(String[] args) { + LinkedList list = new LinkedList(); + list.add(3); + list.add(5); + list.add(6); + list.add(8); +// list.reverse(); + java.util.LinkedList list1 =null; + } +} diff --git a/group17/240094626/work_0305/src/com/coderising/linkedlist/List.java b/group17/240094626/work_0305/src/com/coderising/linkedlist/List.java new file mode 100644 index 0000000000..f1587b17c5 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/linkedlist/List.java @@ -0,0 +1,9 @@ +package com.coderising.linkedlist; + +public interface List { + public void add(E e); + public void add(int index, E e); + public E get(int index); + public E remove(int index); + public int size(); +} diff --git a/group17/240094626/work_0305/src/com/coderising/linkedlist/SLinkedList.java b/group17/240094626/work_0305/src/com/coderising/linkedlist/SLinkedList.java new file mode 100644 index 0000000000..cef0226bb3 --- /dev/null +++ b/group17/240094626/work_0305/src/com/coderising/linkedlist/SLinkedList.java @@ -0,0 +1,119 @@ +package com.coderising.linkedlist; + + +/** + * 单向链表简单实现 + * @author 240094626 + * + */ +public class SLinkedList implements List{ + transient Node head; + transient Node last; + transient int size; + + public SLinkedList(){ + head = new Node(null,last); + last = null; + size = 0; + } + + + private void addAfter(Node n , E e){ + if(n == null){ + last = new Node(e,head); + head.next = last; + }else{ + n.next = new Node(e,n.next); + } + size++; + } + private void checkRange(int index){ + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size); + } + } + + private Node getNode(int index){ + checkRange(index); + Node curr = head; + for(; index >= 0 ; index--){ + curr = curr.next; + } + return curr; + } + + public void add(E e) { + addAfter(last,e); + } + + public void add(int index, E e) { + if(index < 0 || index > size){ + throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size); + } + addAfter(getNode(index-1), e); + } + + public E get(int index) { + Node n = getNode(index); + return n.e; + } + + + public E remove(int index) { + checkRange(index); + Node preN = null, + currN = null; + if(index == 0){ + preN = head; + }else{ + preN = getNode(index-1); + } + currN = preN.next; + preN.next = currN.next; + size--; + return currN.e=null; + + } + + public int size() { + return size; + } + + + private static class Node{ + E e ; + Node next; + + public Node(E e,Node next){ + this.e = e; + this.next = next; + } + } + + private Iterator iterator(){ + return new SLinkedListIterator(); + } + + private class SLinkedListIterator implements Iterator{ + + int index; + public SLinkedListIterator(){ + index = 0; + } + + @Override + public boolean hasNext() { + if(index < size){ + return true; + } + return false; + } + + @Override + public E next() { + Node curr = (Node) getNode(index++); + return curr.e; + } + + } +} diff --git a/group17/333333/.classpath b/group17/333333/.classpath new file mode 100644 index 0000000000..d171cd4c12 --- /dev/null +++ b/group17/333333/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/liuxin/.gitignore b/group17/333333/.gitignore similarity index 100% rename from liuxin/.gitignore rename to group17/333333/.gitignore diff --git a/liuxin/.project b/group17/333333/.project similarity index 89% rename from liuxin/.project rename to group17/333333/.project index b6d8ce6204..4b0233c4cc 100644 --- a/liuxin/.project +++ b/group17/333333/.project @@ -1,6 +1,6 @@ - coding2017 + 333 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/82427129/JavaUtil/src/main/java/com/coding/basic/LinkedList.java b/group17/82427129/JavaUtil/src/main/java/com/coding/basic/LinkedList.java index 1996e43e91..efacab7da8 100644 --- a/group17/82427129/JavaUtil/src/main/java/com/coding/basic/LinkedList.java +++ b/group17/82427129/JavaUtil/src/main/java/com/coding/basic/LinkedList.java @@ -1,46 +1,149 @@ package com.coding.basic; -public class LinkedList implements List { +import java.util.LinkedHashSet; + +public class LinkedList implements List { - private Node head; + private Node head; + private int size; - public void add(Object o){ - + public LinkedList(){} + + public void add(E o){ + add(size, o); } - public void add(int index , Object o){ + public void add(int index , E o){ + rangeCheckforAdd(index); + if(index == 0){ + addFirst(o); + }else{ + addNext(index, o); + } } - public Object get(int index){ - return null; + + private void addNext(int index, E o) { + Node newNode = new Node(o, null); + Node prev = indexOf(index-1); + Node next = prev.next; + newNode.next = next; + prev.next = newNode; + + size++; } - public Object remove(int index){ - return null; + + public void addFirst(E o) { + Node newNode = new Node(o, null); + Node next = head; + head = newNode; + newNode.next = next; + + size++; } - public int size(){ - return -1; + public void addLast(E o){ + add(o); + } + private Node indexOf(int index){ + Node node = head; + for (int i = 0; i < index; i++) { + node = node.next; + } + return node; + } + 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); } - public void addFirst(Object o){ + public E get(int index){ + rangeCheck(index); + return indexOf(index).data; } - public void addLast(Object o){ + public E remove(int index){ + rangeCheck(index); + if(index == 0){ + return removeFirst(); + }else{ + return removeNext(index); + } } - public Object removeFirst(){ - return null; + public void clear(){ + for (Node x = head; x!= null; ) { + Node next = x.next; + x.data = null; + x.next = null; + x = next; + } + size = 0; + head = null; } - public Object removeLast(){ - return null; + + private E removeNext(int index) { + final Node rv = indexOf(index); + final E element = rv.data; + final Node prev = indexOf(index-1); + prev.next = rv.next; + rv.next = null; + size--; + return element; + } + + public int size(){ + return size; + } + + public E removeFirst(){ + final E element = head.data; + final Node rv = head; + final Node next = rv.next; + head = next; + rv.next = null; + size --; + return element; + } + public E removeLast(){ + E e = remove(size-1); + return e; } public Iterator iterator(){ return null; } + @Override + public String toString() { + StringBuilder s = new StringBuilder(); + for (int i = 0; i < size; i++) { + s.append(get(i)).append(","); + } + return s.toString(); + } - - private static class Node{ - Object data; - Node next; + private static class Node{ + E data; + Node next; + public Node(E data,Node next) { + this.data = data; + this.next = next; + } + } + public class ListItr implements Iterator { + + + @Override + public boolean hasNext() { + return false; + } + + @Override + public Object next() { + return null; + } } @@ -48,8 +151,16 @@ private static class Node{ * 把该链表逆置 * 例如链表为 3->7->10 , 逆置后变为 10->7->3 */ - public void reverse(){ - + public void reverse(){ + int i = 1; + if(size == 1 || size == 0){ + return; + } + while(i < size){ + E e = remove(i); + addFirst(e); + i++; + } } /** @@ -58,8 +169,11 @@ public void reverse(){ * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 */ - public void removeFirstHalf(){ - + public void removeFirstHalf(){ + int size = this.size>>1; + for (int i = 0; i < size; i++) { + removeFirst(); + } } /** @@ -67,8 +181,15 @@ public void removeFirstHalf(){ * @param i * @param length */ - public void remove(int i, int length){ + public void remove(int i, int length){ + if(i < 0 ) + throw new IndexOutOfBoundsException("i requested >= 0 ,i:"+i); + if(length < 0) + throw new IndexOutOfBoundsException("length requested > 0 ,length:"+length); + for (int j = 0; j < length&&j list){ + int[] r = new int[list.size]; + for (int i = 0; i < r.length; i++) { + int index = list.get(i); + if(index >= this.size()){ + r[i] = 0; + break; + }else{ + r[i] = (int) this.get(index); + } + } + return r; } /** @@ -89,16 +220,42 @@ public static int[] getElements(LinkedList list){ * @param list */ - public void subtract(LinkedList list){ - + public void subtract(LinkedList list){ + int i = 0;//this list's index + while(i < this.size){ + boolean flag = false; + int j = 0;//parameter list's index + E e = get(i); + + while(j< list.size){ + if(e.equals(list.get(j))){ + remove(i); + flag = true; + break; + }else{ + j++; + } + } + if(!flag){ + i++; + } + } } /** * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) */ - public void removeDuplicateValues(){ - + public void removeDuplicateValues(){ + LinkedHashSet set = new LinkedHashSet(); + for (int i = 0; i < size; i++) { + set.add(get(i)); + } + clear(); + java.util.Iterator iterator = set.iterator(); + while(iterator.hasNext()){ + add(iterator.next()); + } } /** @@ -107,8 +264,16 @@ public void removeDuplicateValues(){ * @param min * @param max */ - public void removeRange(int min, int max){ - + public void removeRange(int min, int max){ + int i = 0; + while(i < size){ + int e = (int)get(i); + if(e > min && e < max){ + remove(i); + }else{ + i++; + } + } } /** @@ -116,7 +281,22 @@ public void removeRange(int min, int max){ * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 * @param list */ - public LinkedList intersection( LinkedList list){ - return null; + public LinkedList intersection( LinkedList list){ + LinkedList linkedList = new LinkedList(); + int i = 0;//this list's index + int j = 0;//parameter list's index + int j2= 0; + while( i < this.size ){ + E e = get(i++); + j = j2+1; + while(j < list.size ){ + if(e.equals(list.get(j))){ + linkedList.add(e); + j2 = j; + } + j++; + } + } + return linkedList; } } diff --git a/group17/82427129/JavaUtil/src/test/java/com/coding/basic/LinkedListTest.java b/group17/82427129/JavaUtil/src/test/java/com/coding/basic/LinkedListTest.java index 304367a0a4..fa76fe64b1 100644 --- a/group17/82427129/JavaUtil/src/test/java/com/coding/basic/LinkedListTest.java +++ b/group17/82427129/JavaUtil/src/test/java/com/coding/basic/LinkedListTest.java @@ -1,81 +1,259 @@ package com.coding.basic; -import static org.junit.Assert.*; - import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class LinkedListTest { - private DoubleNodeLinkedList list; + private LinkedList l =null; @Before public void setUp() throws Exception { - list = new DoubleNodeLinkedList(); + l = new LinkedList() ; } @After public void tearDown() throws Exception { - list = null; + l = null; } @Test - public void testAddObject() { - list.add(100); - Assert.assertEquals(1, list.size()); - list.add(100); - Assert.assertEquals(2, list.size()); - list.add(100); - Assert.assertEquals(3, list.size()); + public void testAddE() { + l.add("1"); + Assert.assertTrue(l.size() == 1); + l.add("1"); + Assert.assertTrue(l.size() == 2); + l.add("1"); + Assert.assertTrue(l.size() == 3); } @Test - public void testAddIntObject() { - for (int i = 0; i < 5; i++) { - list.add(i, i); - } - Assert.assertEquals(5, list.size()); + public void testAddIntE() { + l.add("1"); + l.add("1"); + l.add("1"); + l.add("1"); + l.add(2,"2"); + Assert.assertTrue(l.size() == 5); } @Test - public void testGet() { - + public void testAddFirst() { + l.add("1"); + l.add("1"); + l.add("1"); + l.add("1"); + l.addFirst("first"); + Assert.assertTrue(l.size() == 5); } @Test - public void testRemove() { - fail("Not yet implemented"); + public void testAddLast() { + l.add("1"); + l.add("1"); + l.add("1"); + l.add("1"); + l.addLast("first"); + Assert.assertTrue(l.size() == 5); } @Test - public void testSize() { - fail("Not yet implemented"); + public void testGet() { + l.add("1"); + l.add("1"); + l.add("1"); + l.add("1"); + l.addLast("first"); + Assert.assertTrue(l.get(4).equals("first")); + Assert.assertTrue(l.get(3).equals("1")); } @Test - public void testAddFirst() { - fail("Not yet implemented"); + public void testRemoveInt() { + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + Assert.assertTrue(l.size()==4); + l.remove(2); + Assert.assertTrue(l.size()==3); + Assert.assertTrue(l.get(2).equals("4")); + } + @Test + public void testClear() { + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + Assert.assertTrue(l.size()==4); + l.clear(); + Assert.assertTrue(l.size()==0); } @Test - public void testAddLast() { - fail("Not yet implemented"); + public void testSize() { + Assert.assertTrue(l.size()==0); + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + Assert.assertTrue(l.size()==4); } @Test public void testRemoveFirst() { - fail("Not yet implemented"); + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + l.removeFirst(); + Assert.assertTrue(l.get(0).equals("2")); } @Test public void testRemoveLast() { - fail("Not yet implemented"); + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + Assert.assertTrue(l.size()==4); + Assert.assertTrue(l.get(2).equals("3")); + l.removeLast(); + Assert.assertTrue(l.size()==3); + Assert.assertTrue(l.get(0).equals("1")); + Assert.assertTrue(l.get(1).equals("2")); + Assert.assertTrue(l.get(2).equals("3")); + } + + @Test + public void testReverse() { + l.add("1"); + l.add("2"); + l.add("3"); + l.add("4"); + Assert.assertTrue(l.get(0).equals("1")); + Assert.assertTrue(l.get(1).equals("2")); + Assert.assertTrue(l.get(2).equals("3")); + Assert.assertTrue(l.get(3).equals("4")); + l.reverse(); + Assert.assertTrue(l.get(3).equals("1")); + Assert.assertTrue(l.get(2).equals("2")); + Assert.assertTrue(l.get(1).equals("3")); + Assert.assertTrue(l.get(0).equals("4")); + } + + @Test + public void testRemoveFirstHalf() { + l.add("2"); + l.add("5"); + l.add("7"); + l.add("8"); + l.add("9"); + Assert.assertTrue(l.size()==5); + l.removeFirstHalf(); + Assert.assertTrue(l.size()==3); + Assert.assertTrue(l.get(0).equals("7")); + Assert.assertTrue(l.get(1).equals("8")); + Assert.assertTrue(l.get(2).equals("9")); + } + + @Test + public void testRemoveIntInt() { + l.add("2"); + l.add("5"); + l.add("7"); + l.add("8"); + l.add("9"); + l.remove(2, 2); + Assert.assertTrue(l.get(0).equals("2")); + Assert.assertTrue(l.get(1).equals("5")); + Assert.assertTrue(l.get(2).equals("9")); + Assert.assertTrue(l.size()==3); + } + + @Test + public void testGetElements() { + LinkedList l = new LinkedList(); + l.add(2); + l.add(5); + l.add(7); + l.add(8); + l.add(9); + LinkedList l2 = new LinkedList(); + l2.add(1); + l2.add(2); + l2.add(4); + int[] elements = l.getElements(l2); + int[] exp = {5,7,9}; + Assert.assertArrayEquals(exp, elements); + } + + @Test + public void testSubtract() { + l.add("2"); + l.add("5"); + l.add("7"); + l.add("8"); + l.add("9"); + LinkedList l2 = new LinkedList(); + l2.add("2"); + l2.add("9"); + l2.add("8"); + l.subtract(l2); + Assert.assertTrue(l.size()==2); + Assert.assertTrue(l.get(0).equals("5")); + Assert.assertTrue(l.get(1).equals("7")); + } + + @Test + public void testRemoveDuplicateValues() { + l.add("2"); + l.add("5"); + l.add("5"); + l.add("8"); + l.add("8"); + l.removeDuplicateValues(); + Assert.assertTrue(l.size()==3); + Assert.assertTrue(l.get(0).equals("2")); + Assert.assertTrue(l.get(1).equals("5")); + Assert.assertTrue(l.get(2).equals("8")); + } + + @Test + public void testRemoveRange() { + LinkedList l = new LinkedList(); + l.add(2); + l.add(5); + l.add(7); + l.add(8); + l.add(9); + System.out.println(l); + l.removeRange(3, 7); + System.out.println(l); + Assert.assertTrue(l.size()==4); + Assert.assertTrue(l.get(0)==2); + Assert.assertTrue(l.get(1)==7); + Assert.assertTrue(l.get(2)==8); + Assert.assertTrue(l.get(3)==9); } @Test - public void testIterator() { - fail("Not yet implemented"); + public void testIntersection() { + l.add("2"); + l.add("5"); + l.add("7"); + l.add("8"); + l.add("9"); + LinkedList l2 = new LinkedList(); + l2.add("1"); + l2.add("2"); + l2.add("3"); + l2.add("5"); + LinkedList intersection = l.intersection(l2); + Assert.assertTrue(intersection.size()==2); + Assert.assertTrue(intersection.get(0).equals("2")); + Assert.assertTrue(intersection.get(1).equals("5")); } } diff --git a/group17/article/20170305-20170312.md b/group17/article/20170305-20170312.md index f43f5b5fb2..821a539928 100644 --- a/group17/article/20170305-20170312.md +++ b/group17/article/20170305-20170312.md @@ -20,9 +20,9 @@ 1059107701 -240094626 +240094626 http://note.youdao.com/noteshare?id=2a29168e06f3942719478584968505a6 -82427129 +82427129 http://blog.csdn.net/walk_er/article/details/60570932 296910598 @@ -53,4 +53,3 @@ 1368331120 517970312 - 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/liuxin/src/com/coderising/download/api/ConnectionException.java b/group20/404130810/src/com/coderising/download/api/ConnectionException.java similarity index 100% rename from liuxin/src/com/coderising/download/api/ConnectionException.java rename to group20/404130810/src/com/coderising/download/api/ConnectionException.java 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/group12/495473393/Coding/src/Base/Stack.java b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java similarity index 77% rename from group12/495473393/Coding/src/Base/Stack.java rename to group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java index 8f59343d4b..09f83c98b6 100644 --- a/group12/495473393/Coding/src/Base/Stack.java +++ b/group20/592146505/592146505Learning/src/org/wsc/coding/basic/stack/Stack.java @@ -1,4 +1,6 @@ -package Base; +package org.wsc.coding.basic.stack; + +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/liuxin/src/com/coderising/array/ArrayUtil.java b/group20/755659358/week03/src/com/coderising/array/ArrayUtil.java similarity index 100% rename from liuxin/src/com/coderising/array/ArrayUtil.java rename to group20/755659358/week03/src/com/coderising/array/ArrayUtil.java 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/liuxin/src/com/coderising/download/api/Connection.java b/group20/755659358/week03/src/com/coderising/download/api/Connection.java similarity index 100% rename from liuxin/src/com/coderising/download/api/Connection.java rename to group20/755659358/week03/src/com/coderising/download/api/Connection.java 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/liuxin/src/com/coderising/litestruts/LoginAction.java b/group20/755659358/week03/src/com/coderising/litestruts/LoginAction.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/LoginAction.java rename to group20/755659358/week03/src/com/coderising/litestruts/LoginAction.java diff --git a/liuxin/src/com/coderising/litestruts/Struts.java b/group20/755659358/week03/src/com/coderising/litestruts/Struts.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/Struts.java rename to group20/755659358/week03/src/com/coderising/litestruts/Struts.java diff --git a/liuxin/src/com/coderising/litestruts/StrutsTest.java b/group20/755659358/week03/src/com/coderising/litestruts/StrutsTest.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/StrutsTest.java rename to group20/755659358/week03/src/com/coderising/litestruts/StrutsTest.java diff --git a/liuxin/src/com/coderising/litestruts/View.java b/group20/755659358/week03/src/com/coderising/litestruts/View.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/View.java rename to group20/755659358/week03/src/com/coderising/litestruts/View.java 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/group22/.gitignore b/group22/.gitignore new file mode 100644 index 0000000000..d1945e125c --- /dev/null +++ b/group22/.gitignore @@ -0,0 +1 @@ +/627559964/ diff --git a/liuxin/.classpath b/group22/1014331282/Mywork_LX/.classpath similarity index 77% rename from liuxin/.classpath rename to group22/1014331282/Mywork_LX/.classpath index 2d7497573f..373dce4005 100644 --- a/liuxin/.classpath +++ b/group22/1014331282/Mywork_LX/.classpath @@ -1,7 +1,7 @@ - - - - - - - + + + + + + + diff --git a/group22/1014331282/Mywork_LX/.project b/group22/1014331282/Mywork_LX/.project new file mode 100644 index 0000000000..1290d27942 --- /dev/null +++ b/group22/1014331282/Mywork_LX/.project @@ -0,0 +1,17 @@ + + + Mywork_LX + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group22/1014331282/Mywork_LX/.settings/org.eclipse.jdt.core.prefs b/group22/1014331282/Mywork_LX/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..3a21537071 --- /dev/null +++ b/group22/1014331282/Mywork_LX/.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/group22/1014331282/Mywork_LX/src/week1_0306/ArrayList.java b/group22/1014331282/Mywork_LX/src/week1_0306/ArrayList.java new file mode 100644 index 0000000000..5446c9b557 --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/ArrayList.java @@ -0,0 +1,114 @@ +package week1_0306; + + + +public class ArrayList implements List +{ + + private int size; + + private Object[] elementData ; + + public ArrayList() + { + elementData = new Object[3]; + size=-1; + } + + public void add(Object o) + { + if(size >= elementData.length-1) + { + Object[] replaceData=new Object[elementData.length+5]; + System.arraycopy(elementData, 0, replaceData, 0, elementData.length); + elementData = replaceData; + } + elementData[++size] = o; + } + + public void add(int index, Object o) + { + Object[] replaceData=new Object[11]; + for(int i=0;i=0 && size>=0) + return elementData[index]; + else return null; + } + + + public Object remove(int index) + { + size--; + Object o=elementData[index]; + if (index0) + { + for(int i=index;i=0) + return size+1; + else + return 0; + } + + 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; + } + + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + pos++; + if(pos > size) + return false; + else return true; + } + + @Override + public Object next() { + // TODO Auto-generated method stub + return elementData[pos]; + + } + + public Object remove() + { + return this.l.remove(pos); + } + + } + +} diff --git a/group22/1014331282/Mywork_LX/src/week1_0306/BinaryTree.java b/group22/1014331282/Mywork_LX/src/week1_0306/BinaryTree.java new file mode 100644 index 0000000000..e5b23d37ce --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/BinaryTree.java @@ -0,0 +1,135 @@ +package week1_0306; + +import java.util.Comparator; + +import week1_0306.BinaryTree.BinaryTreeNode; + +public class BinaryTree +{ + private BinaryTreeNode root; + + private BinaryTreeNode pointer; + + public BinaryTreeNode getRoot() { + return root; + } + + public void setRoot(BinaryTreeNode root) { + this.root = root; + } + + public BinaryTreeNode getPointer() { + return pointer; + } + + public void setPointer(BinaryTreeNode pointer) { + this.pointer = pointer; + } + + public BinaryTree() + { + root=new BinaryTreeNode(); + pointer=root; + } + + public BinaryTreeNode insert(Object o,Comparator c) + { + + pointer= root.insert(o, c); + return pointer; + } + + public void printTree() + { + root.printNode(); + } + + 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() { + pointer=left; + return left; + } + + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + + public BinaryTreeNode getRight() { + pointer=right; + return right; + } + + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + + + public BinaryTreeNode insert(Object o, Comparator c) //йɵ+ + { + if(this.data == null) + { + this.data = o; + return this; + } + + int i = c.compare(this.data,o); + + if( i > 0 ) + { + if(this.left == null) + { + this.left=new BinaryTreeNode(); + this.left.data=o; + return this.left; + } + else + return this.left.insert(o, c); + } + else if(i < 0) + { + if(this.right == null) + { + this.right=new BinaryTreeNode(); + this.right.data = o; + return this.right; + } + + else + return this.right.insert(o, c); + } + else + { + return this; + } + + } + + public void printNode() + { + ScoreRecord s=(ScoreRecord)(this.getData()); + System.out.println(s.getName()+" "+s.getId()); + if(this.getLeft()!=null) + this.getLeft().printNode(); + if(this.getRight()!=null) + this.getRight().printNode(); + else return; + } + + } + +} diff --git a/group22/1014331282/Mywork_LX/src/week1_0306/Iterator.java b/group22/1014331282/Mywork_LX/src/week1_0306/Iterator.java new file mode 100644 index 0000000000..26471af1cd --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/Iterator.java @@ -0,0 +1,9 @@ +package week1_0306; + +public interface Iterator { + + public boolean hasNext(); + public Object next(); + public Object remove(); + +} diff --git a/group22/1014331282/Mywork_LX/src/week1_0306/LinkedList.java b/group22/1014331282/Mywork_LX/src/week1_0306/LinkedList.java new file mode 100644 index 0000000000..e540a7c115 --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/LinkedList.java @@ -0,0 +1,181 @@ +package week1_0306; + + + +public class LinkedList implements List +{ + private Node head; + + private static int size = 0; + + public LinkedList() + { + head=new Node(); + + } + + + private static class Node + { + Object data; + Node next; + } + + public void add(Object o) + { + Node h = head; + while(h.next!= null) + { + h=h.next; + } + Node p = new Node(); + p.data=o; + p.next=null; + h.next= p; + + size++; + } + + public void add(int index, Object o) + { + Node h=head.next; + int i=0; + while(i size) + return false; + else return true; + } + + @Override + public Object next() { + // TODO Auto-generated method stub + return l.get(pos); + + } + + public Object remove() + { + return this.l.remove(pos); + } + + } + + +} + diff --git a/group13/1274639949/lesson01/src/com/hans/List.java b/group22/1014331282/Mywork_LX/src/week1_0306/List.java similarity index 86% rename from group13/1274639949/lesson01/src/com/hans/List.java rename to group22/1014331282/Mywork_LX/src/week1_0306/List.java index f8ffaa8f5e..7ec758f832 100644 --- a/group13/1274639949/lesson01/src/com/hans/List.java +++ b/group22/1014331282/Mywork_LX/src/week1_0306/List.java @@ -1,10 +1,18 @@ -package com.hans; +package week1_0306; + + 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(); } diff --git a/group22/1014331282/Mywork_LX/src/week1_0306/Queue.java b/group22/1014331282/Mywork_LX/src/week1_0306/Queue.java new file mode 100644 index 0000000000..e9c32b8e68 --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/Queue.java @@ -0,0 +1,35 @@ +package week1_0306; + +public class Queue { + + private LinkedList queue = new LinkedList(); + + public void enQueue(Object o)// + { + queue.addFirst(o); + } + + public Object deQueue()// + { + return queue.removeLast(); + } + + public boolean isEmpty() + { + if(queue.get(0)==null) + return true; + else return false; + } + + public int size() + { + return queue.size(); + } + + public Queue() { + // TODO Auto-generated constructor stub + } + + + +} diff --git a/group22/1014331282/Mywork_LX/src/week1_0306/ScoreRecord.java b/group22/1014331282/Mywork_LX/src/week1_0306/ScoreRecord.java new file mode 100644 index 0000000000..f3bce47950 --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/ScoreRecord.java @@ -0,0 +1,180 @@ +package week1_0306; +/* +ʾ¼뼸ѧϢ +¼ѧųɼ +ӡѧѧӢɼߵǸ +ͳÿſεƽɼܳɼƽֵ +װ +*/ +import java.util.Scanner; +import java.util.Comparator; + +public class ScoreRecord implements Comparator +{ + + private int id; + private String name; + private float C_Score; + private float M_Score; + private float E_Score; + + public ScoreRecord(){}; + + public ScoreRecord(int id,String name,float C_Score, float M_Score, float E_Score) + { + this.id=id; + this.name=name; + this.C_Score=C_Score; + this.E_Score=E_Score; + this.M_Score=M_Score; + } + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public float getC_Score() { + return C_Score; + } + + public void setC_Score(float c_Score) { + C_Score = c_Score; + } + + public float getM_Score() { + return M_Score; + } + + public void setM_Score(float m_Score) { + M_Score = m_Score; + } + + public float getE_Score() { + return E_Score; + } + + public void setE_Score(float e_Score) { + E_Score = e_Score; + } + + public int compare(Object o1, Object o2) + { + ScoreRecord s1 = (ScoreRecord) o1; + ScoreRecord s2 = (ScoreRecord) o2; + if(s1.id>s2.id) + return 1; + else if(s1.id==s2.id) + return 0; + else + return -1; + } + + public int compareTo(Object o1) + { + ScoreRecord s = (ScoreRecord) o1; + if(this.id>s.id) + return 1; + else if(this.id==s.id) + return 0; + else return -1; + } + + public static void readData(ScoreRecord[] arr) + { + Scanner a=new Scanner(System.in); + 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; + } +} + + \ No newline at end of file diff --git a/group22/1158477486/src/TestCollection/List.java b/group22/1158477486/src/TestCollection/List.java new file mode 100644 index 0000000000..1b14c3ebe6 --- /dev/null +++ b/group22/1158477486/src/TestCollection/List.java @@ -0,0 +1,9 @@ +package TestCollection; + +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/group22/1158477486/src/TestCollection/Queue.java b/group22/1158477486/src/TestCollection/Queue.java new file mode 100644 index 0000000000..4699235e98 --- /dev/null +++ b/group22/1158477486/src/TestCollection/Queue.java @@ -0,0 +1,38 @@ +package TestCollection; + + ; + +public class Queue { + private LinkedList list=new LinkedList(); + + public void enQueue(Object o){ + list.addLast ( o) ;//add(index, o) + } + + public Object deQueue(){ + Object o=list.get(1); + list.remove(1); + return o; + } + + public boolean isEmpty(){ + if(list.size()!=0){ + return false;}else + return true; + } + + public int size(){ + return list.size(); + } + public static void main(String[] args) { + Queue q=new Queue(); + q.enQueue("1"); + q.enQueue("2"); + q.enQueue("3"); + System.out.println(q.size()); + Object o=q.deQueue(); + System.out.println(o); + System.out.println(q.size()); + + } +} diff --git a/group22/1158477486/src/TestCollection/Stack.java b/group22/1158477486/src/TestCollection/Stack.java new file mode 100644 index 0000000000..35fdc6f31b --- /dev/null +++ b/group22/1158477486/src/TestCollection/Stack.java @@ -0,0 +1,36 @@ +package TestCollection; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + return elementData.get(elementData.size()-1) ; + } + + public Object peek(){ + elementData.remove(elementData.size()-1); + 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 s=new Stack(); + s.push("111"); + s.push("211"); + s.push("311"); + System.out.println(s.size());//3 + System.out.println(s.pop()); + System.out.println(s.size()); + System.out.println(s.peek()); + System.out.println(s.size()); + }} diff --git a/group22/1193590951/githubitem/bin/com/github/mrwengq/sec/struts.xml b/group22/1193590951/githubitem/bin/com/github/mrwengq/sec/struts.xml new file mode 100644 index 0000000000..404aa778e1 --- /dev/null +++ b/group22/1193590951/githubitem/bin/com/github/mrwengq/sec/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayList.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayList.java new file mode 100644 index 0000000000..d9d8356b67 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayList.java @@ -0,0 +1,110 @@ +package com.github.mrwengq.first; + +public class ArrayList implements List { + + private int size = 0; + private Object elementData[] = new Object[5]; + + public void add(Object o) { + if (size >= elementData.length) + elementData = copyAddArray(elementData); + elementData[size] = o; + size++; + } + + public void add(int index, Object o) { + if (index > size - 1 || index < 0) { + throw new ArrayIndexOutOfBoundsException(); + } else { + elementData = addUpdateArray(elementData, index); + elementData[index] = o; + size++; + return; + } + } + + public Object get(int index) { + if (index > size - 1 || index < 0) + throw new ArrayIndexOutOfBoundsException(); + else + return elementData[index]; + } + + public Object remove(int index) { + if (index > size - 1 || index < 0) + throw new ArrayIndexOutOfBoundsException(); + if (index == size - 1) { + elementData[index] = null; + size--; + return null; + } else { + delUpdateArray(elementData, index); + size--; + return null; + } + } + + public int size() { + return size; + } + + public Iterator iterator() { + return new Iterator() { + + int index=-1; + + public boolean hasNext() { + index++; + if(index index) {//判断受影响索引 + temp = elementData[index]; + elementData[index] = elementData[i]; + elementData[i] = temp; + if (i == size - 1) { //判断为最后一位 + if (size > elementData.length) + elementData = copyAddArray(elementData); + elementData[size] = elementData[index]; + } + } + + return elementData; + } + + private void delUpdateArray(Object elementData[], int index) {//删除时修改索引 + for (int i = 0; i < size; i++){ + + if (i > index && i < size ){//判断受影响索引 + elementData[i - 1] = elementData[i]; + if (i == size - 1){ + elementData[i] = null; + } + } + + } + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayListTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayListTest.java new file mode 100644 index 0000000000..000ad6e813 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/ArrayListTest.java @@ -0,0 +1,112 @@ +package com.github.mrwengq.first; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ArrayListTest { + ArrayList list = new ArrayList(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAddObject() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + list.add(6); + list.add(7); + int[] o = new int[] { 1, 2, 3, 4, 5, 6, 7 }; + for (int i = 0; i < list.size(); i++) { + assertEquals(o[i], o[i]); + } + + } + + @Test + public void testAddIntObject() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + list.add(6); + list.add(7); + list.add(5, 9); + int[] o = new int[] { 1, 2, 3, 4, 5, 9, 6, 7 }; + for (int i = 0; i < list.size(); i++) { + assertEquals(o[i], o[i]); + } + } + + @Test + public void testGet() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + list.add(6); + list.add(7); + assertEquals(list.get(5), 6); + assertEquals(list.get(2), 3); + assertEquals(list.get(4), 5); + assertEquals(list.get(6), 7); + } + + @Test + public void testRemove() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + list.remove(3); + assertEquals(list.get(3), 5); + } + + @Test + public void testSize() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + assertEquals(list.size(), 5); + } + + @Test + public void testIterator() { + ArrayList list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); + Iterator iter = list.iterator(); + int i = 0; + int[] o = new int[] { 1, 2, 3, 4, 5}; + + while(iter.hasNext()){ + + assertEquals(iter.next(),o[i]); + i++; + } + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNode.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNode.java new file mode 100644 index 0000000000..f832e10521 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNode.java @@ -0,0 +1,98 @@ +package com.github.mrwengq.first; + +import java.util.Comparator; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private Comparator cpt; + public BinaryTreeNode() { + cpt = new Comparator() { + + public int compare(Object o1, Object o2) { + int ob1 = ((Integer) o1).intValue(); + int ob2 = ((Integer) o2).intValue(); + if (ob1 > ob2){ + return 1; + } + if(ob1 0) { + if (getLeft() == null) { + this.setLeft(tree); + return null; + } + left.insert(o); + } else if (comValue < 0) { + if (getRight() == null) { + this.setRight(tree); + return null; + } + right.insert(o); + } + return null; + } + //新加入的方法用于获取节点,帮助测试insert + public BinaryTreeNode findNode(Object o){ + + + if((int)this.data == (int)o){ + return this; + + }else if((int)this.data > (int)o){ + if(this.left!=null){ + return this.left.findNode(o); + } + return null; + }else if((int)this.data <(int)o){ + if(this.right!=null){ + return this.right.findNode(o); + } + return null; + } + return null; + + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNodeTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..44fad39594 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/BinaryTreeNodeTest.java @@ -0,0 +1,37 @@ +package com.github.mrwengq.first; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class BinaryTreeNodeTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testInsert() { + BinaryTreeNode btnt = new BinaryTreeNode(); + btnt.insert(15); + btnt.insert(16); + btnt.insert(23); + btnt.insert(10); + btnt.insert(18); + btnt.insert(9); + + assertEquals(btnt.getData(), 15); + assertEquals(btnt.getLeft().getData(),10); + assertEquals(btnt.getRight().getData(),16); + assertEquals(btnt.findNode(16).getRight().getData(),23); + assertEquals(btnt.findNode(23).getLeft().getData(),18); + assertEquals(btnt.findNode(10).getLeft().getData(),9); + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/Iterator.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Iterator.java new file mode 100644 index 0000000000..2947813ffd --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Iterator.java @@ -0,0 +1,10 @@ +package com.github.mrwengq.first; + + +public interface Iterator +{ + + public abstract boolean hasNext(); + + public abstract Object next(); +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedList.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedList.java new file mode 100644 index 0000000000..1dc4dd4342 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedList.java @@ -0,0 +1,250 @@ +package com.github.mrwengq.first; + +public class LinkedList implements List { + private Node head; + private int size =0; + private static class Node { + + Object data; + Node next; + + public Node(Object o) { + data = o; + next = null; + } + } + + + public void add(Object o) { + if (size == 0) { + head = new Node(o); + } else { + Node node = new Node(o); + Node lastNode = findNode(size-1); + lastNode.next = node; + } + size++; + } + + private Node findNode(int index) { + Node no = head; + for (; index > 0; index--) + no = no.next; + + return no; + } + + public void add(int index, Object o) { + if (index < 0 || index > size - 1) + throw new ArrayIndexOutOfBoundsException(); + Node node = new Node(o); + Node indexNode = findNode(index); + if (index - 1 < 0) { + node.next = indexNode; + head = node; + size++; + return; + } else { + Node lastNode = findNode(index - 1); + lastNode.next = node; + node.next = indexNode; + size++; + return; + } + } + + public Object get(int index) { + if (index < 0 || index > size - 1) + throw new ArrayIndexOutOfBoundsException(); + else + return findNode(index).data; + } + + public Object remove(int index) { + if (index < 0 || index > size - 1 || size == 0) + throw new ArrayIndexOutOfBoundsException(); + Node indexNode = findNode(index); + if (size == 1) { + head = null; + size = 0; + return indexNode.data; + } + Node nextNode = null; + Node lastNode = null; + if (index + 1 <= size - 1) //判断是否有下一位 + nextNode = findNode(index + 1); + if (index - 1 > 0) //判断是否有上一位 + lastNode = findNode(index - 1); + if (lastNode == null) { + head = nextNode; + size--; + return indexNode.data; + }else if (nextNode == null) { + lastNode.next = null; + size--; + return indexNode.data; + } else { + lastNode.next = nextNode; + size--; + return indexNode.data; + } + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + Node node = new Node(o); + if (size == 0) { + head = node; + size++; + return; + } else { + node.next = head; + head = node; + size++; + return; + } + } + + public void addLast(Object o) { + Node node = new Node(o); + if (size == 0) { + head = node; + size++; + return; + } else { + Node lastNode = findNode(size-1); + lastNode.next = node; + size++; + return; + } + } + + public Object removeFirst() { + if (size == 0) { + return null; + } else { + Node nextNode = head.next; + Object ob = head.data; + head = nextNode; + size--; + return ob; + } + } + + public Object removeLast() { + if (size == 0) { + return null; + } else { + Node node = findNode(size-1); //size -1 为最后一位 -2为前一位 + if(size-2>=0){ + Node lastNode = findNode(size - 2); + lastNode.next = null; + } + size--; + return node.data; + } + } + + public Iterator iterator() { + return new Iterator() { + + int index = -1; + + public boolean hasNext() { + index++; + if(index7->10 , 閫嗙疆鍚庡彉涓� 10->7->3 + */ + public void reverse(){ + + } + + /** + * 鍒犻櫎涓�釜鍗曢摼琛ㄧ殑鍓嶅崐閮ㄥ垎 + * 渚嬪锛歭ist = 2->5->7->8 , 鍒犻櫎浠ュ悗鐨勫�涓�7->8 + * 濡傛灉list = 2->5->7->8->10 ,鍒犻櫎浠ュ悗鐨勫�涓�,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 浠庣i涓厓绱犲紑濮嬶紝 鍒犻櫎length 涓厓绱�锛�娉ㄦ剰i浠�寮� + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 鍋囧畾褰撳墠閾捐〃鍜宭ist鍧囧寘鍚凡鍗囧簭鎺掑垪鐨勬暣鏁� + * 浠庡綋鍓嶉摼琛ㄤ腑鍙栧嚭閭d簺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涓斿皬浜巑ax鐨勫厓绱狅紙鑻ヨ〃涓瓨鍦ㄨ繖鏍风殑鍏冪礌锛� + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 鍋囪褰撳墠閾捐〃鍜屽弬鏁發ist鎸囧畾鐨勯摼琛ㄥ潎浠ュ厓绱犱緷鍊奸�澧炴湁搴忔帓鍒楋紙鍚屼竴琛ㄤ腑鐨勫厓绱犲�鍚勪笉鐩稿悓锛� + * 鐜拌姹傜敓鎴愭柊閾捐〃C锛屽叾鍏冪礌涓哄綋鍓嶉摼琛ㄥ拰list涓厓绱犵殑浜ら泦锛屼笖琛–涓殑鍏冪礌鏈変緷鍊奸�澧炴湁搴忔帓鍒� + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedListTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedListTest.java new file mode 100644 index 0000000000..254aa95c53 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/LinkedListTest.java @@ -0,0 +1,216 @@ +package com.github.mrwengq.first; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class LinkedListTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAddObject() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + + + } + + @Test + public void testAddIntObject() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.add(3, "6"); + assertEquals(li.get(0), "1"); + assertEquals(li.get(1), "2"); + assertEquals(li.get(2), "3"); + assertEquals(li.get(3), "6"); + assertEquals(li.get(4), "4"); + assertEquals(li.get(5), "5"); + + } + + @Test + public void testGet() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + assertEquals(li.get(0), "1"); + assertEquals(li.get(1), "2"); + assertEquals(li.get(2), "3"); + assertEquals(li.get(3), "4"); + assertEquals(li.get(4), "5"); + + + } + + @Test + public void testRemoveInt() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.remove(3); + assertEquals(li.get(0), "1"); + assertEquals(li.get(1), "2"); + assertEquals(li.get(2), "3"); + assertEquals(li.get(3), "5"); + + } + + @Test + public void testSize() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + assertEquals(li.size(), 5); + } + + @Test + public void testAddFirst() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.addFirst("6"); + assertEquals(li.get(0), "6"); + assertEquals(li.get(1), "1"); + assertEquals(li.get(2), "2"); + assertEquals(li.get(3), "3"); + assertEquals(li.get(4), "4"); + assertEquals(li.get(5), "5"); + } + + @Test + public void testAddLast() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.addLast("6"); + assertEquals(li.get(0), "1"); + assertEquals(li.get(1), "2"); + assertEquals(li.get(2), "3"); + assertEquals(li.get(3), "4"); + assertEquals(li.get(4), "5"); + assertEquals(li.get(5), "6"); + } + + @Test + public void testRemoveFirst() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.removeFirst(); + assertEquals(li.get(0), "2"); + assertEquals(li.get(1), "3"); + assertEquals(li.get(2), "4"); + assertEquals(li.get(3), "5"); + } + + @Test + public void testRemoveLast() { + LinkedList li = new LinkedList(); + li.add("1"); + li.add("2"); + li.add("3"); + li.add("4"); + li.add("5"); + li.removeLast(); + assertEquals(li.get(0), "1"); + assertEquals(li.get(1), "2"); + assertEquals(li.get(2), "3"); + assertEquals(li.get(3), "4"); + } + + @Test + public void testIterator() { + LinkedList list = new LinkedList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + Iterator iter = list.iterator(); + int i = 0; + String [] o = new String[] { "1","2", "3","4", "5"}; + + while(iter.hasNext()){ + + assertEquals(iter.next(),o[i]); + i++; + }; + } + + @Test + public void testReverse() { + fail("Not yet implemented"); + } + + @Test + public void testRemoveFirstHalf() { + fail("Not yet implemented"); + } + + @Test + public void testRemoveIntInt() { + fail("Not yet implemented"); + } + + @Test + public void testGetElements() { + fail("Not yet implemented"); + } + + @Test + public void testSubtract() { + fail("Not yet implemented"); + } + + @Test + public void testRemoveDuplicateValues() { + fail("Not yet implemented"); + } + + @Test + public void testRemoveRange() { + fail("Not yet implemented"); + } + + @Test + public void testIntersection() { + fail("Not yet implemented"); + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/List.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/List.java new file mode 100644 index 0000000000..d36d04b8b6 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/List.java @@ -0,0 +1,16 @@ +package com.github.mrwengq.first; + + +public interface List +{ + + public abstract void add(Object obj); + + public abstract void add(int i, Object obj); + + public abstract Object get(int i); + + public abstract Object remove(int i); + + public abstract int size(); +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/Queue.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Queue.java new file mode 100644 index 0000000000..004ac39e6b --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Queue.java @@ -0,0 +1,29 @@ +package com.github.mrwengq.first; + +public class Queue { + + private ArrayList elementData; + public Queue() { + elementData = new ArrayList(); + } + + public void enQueue(Object o) { + elementData.add(o); + } + + public Object deQueue() { + Object ob = null; + ob = elementData.get(0); + elementData.remove(0); + return ob; + } + + public boolean isEmpty() { + return elementData.size() == 0; + } + + public int size() { + return elementData.size(); + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/QueueTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/QueueTest.java new file mode 100644 index 0000000000..3dac4c4671 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/QueueTest.java @@ -0,0 +1,76 @@ +package com.github.mrwengq.first; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class QueueTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + Queue qu = new Queue(); + + @Test + public void testEnQueue() { + Queue qu = new Queue(); + qu.enQueue("12"); + qu.enQueue("16"); + qu.enQueue("22"); + qu.enQueue("11"); + qu.enQueue("62"); + + + } + + @Test + public void testDeQueue() { + Queue qu = new Queue(); + qu.enQueue("12"); + qu.enQueue("16"); + qu.enQueue("22"); + qu.enQueue("11"); + qu.enQueue("62"); + assertEquals(qu.deQueue(), 12+""); + assertEquals(qu.deQueue(), 16+""); + assertEquals(qu.deQueue(), 22+""); + assertEquals(qu.deQueue(), 11+""); + assertEquals(qu.deQueue(), 62+""); + + } + + @Test + public void testIsEmpty() { + Queue qu = new Queue(); + qu.enQueue("12"); + qu.enQueue("16"); + qu.enQueue("22"); + qu.enQueue("11"); + qu.enQueue("62"); + assertEquals(qu.deQueue(), 12+""); + assertEquals(qu.deQueue(), 16+""); + assertEquals(qu.deQueue(), 22+""); + assertEquals(qu.deQueue(), 11+""); + assertEquals(qu.deQueue(), 62+""); + assertEquals(qu.isEmpty(),true); + } + + @Test + public void testSize() { + Queue qu = new Queue(); + qu.enQueue("12"); + qu.enQueue("16"); + qu.enQueue("22"); + qu.enQueue("11"); + qu.enQueue("62"); + assertEquals(qu.size(), 5); + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/Stack.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Stack.java new file mode 100644 index 0000000000..e718234386 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/Stack.java @@ -0,0 +1,47 @@ +package com.github.mrwengq.first; + +public class Stack { + + + private ArrayList elementData; + private int index = 0; + public Stack() { + elementData = new ArrayList(); + } + + public void push(Object o) { + elementData.add(o); + } + + public Object pop() { + if (elementData.size() == 0) { + return null; + } else { + Object ob = null; + ob = elementData.get(elementData.size() - 1); + elementData.remove(elementData.size() - 1); + return ob; + } + } + + public Object peek() { + if (elementData.size() == 0){ + return null; + }else{ + index ++; + Object ob = index>elementData.size()? null:elementData.get(elementData.size() - index); + if(ob==null){ + index = 0; + } + return ob; + } + } + + public boolean isEmpty() { + return elementData.size() == 0; + } + + public int size() { + return elementData.size(); + } +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/first/StackTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/first/StackTest.java new file mode 100644 index 0000000000..7cea2aa985 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/first/StackTest.java @@ -0,0 +1,88 @@ +package com.github.mrwengq.first; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class StackTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testPush() { + Stack st =new Stack(); + st.push("1"); + st.push("2"); + st.push("3"); + st.push("4"); + st.push("5"); + + } + + @Test + public void testPop() { + Stack st =new Stack(); + st.push("1"); + st.push("2"); + st.push("3"); + st.push("4"); + st.push("5"); + assertEquals(st.pop(), "5"); + assertEquals(st.pop(), "4"); + assertEquals(st.pop(), "3"); + assertEquals(st.pop(), "2"); + assertEquals(st.pop(), "1"); + assertEquals(st.isEmpty(),true); + } + + @Test + public void testPeek() { + Stack st =new Stack(); + st.push("1"); + st.push("2"); + st.push("3"); + st.push("4"); + st.push("5"); + assertEquals(st.peek(), "5"); + assertEquals(st.peek(), "4"); + assertEquals(st.peek(), "3"); + assertEquals(st.peek(), "2"); + assertEquals(st.peek(), "1"); + assertEquals(st.isEmpty(),false); + } + + @Test + public void testIsEmpty() { + Stack st =new Stack(); + assertEquals(st.isEmpty(),true); + st.push("1"); + st.push("2"); + st.push("3"); + st.push("4"); + st.push("5"); + assertEquals(st.isEmpty(),false); + + } + + @Test + public void testSize() { + Stack st =new Stack(); + assertEquals(st.size(),0); + st.push("1"); + st.push("2"); + st.push("3"); + st.push("4"); + st.push("5"); + assertEquals(st.size(),5); + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/sec/ArrayUtil.java b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/ArrayUtil.java new file mode 100644 index 0000000000..3b037d2cc9 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/ArrayUtil.java @@ -0,0 +1,252 @@ +package com.github.mrwengq.sec; + +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 = len ; i>0;i--){ //len - i 是从小到大 + if(len - i > (int) (len-1)/2){ + break; + } + temp = origin[len-i]; + origin[len-i] = origin[i-1]; //i-1是从大到小 + origin[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 removeNum =0; + for(int i = 0;iarray1.length-1){ + newArray[i] = array2[index2++]; + break; + } + if(index2>array2.length-1){ + newArray[i] = array1[index1++]; + break; + } + if(array1[index1]>array2[index2]){ + newArray[i] = array2[index2++]; + }else if(array1[index1]max){ + break; + } + if(len-1>temp.length){ + temp = copyAddArray(temp); + } + temp[len] = next; + len++; + + } + int[] fbn = new int[len]; + System.arraycopy(temp, 0, fbn, 0, len); + return fbn; + } + private int[] copyAddArray(int elementData[]) { //对数组扩容 增加量为原长度3/4 + int ob[] = new int[elementData.length+(elementData.length * 3) / 4]; + System.arraycopy(elementData ,0, ob, 0,elementData.length); + return ob; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max<3){ + return null; + } + int[] temp = new int[100]; + int index = 0; + int i = 2;//最小素数 + while(itemp.length-1){ //判断空间是否充足,否扩容 + temp = copyAddArray(temp); + } + temp[index++] = i; + i++; + } + int[] prime = new int[index]; + System.arraycopy(temp, 0, prime, 0, index); + return prime; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + if(max <2){ + return null; + } + + int[] temp = new int[100]; + int index = 0; + int i = 2; + while(itemp.length-1){ //判断空间是否充足,否扩容 + temp = copyAddArray(temp); + } + temp[index++] = i; + i++; + } + if(0==index){ + return null; + } + int[] perfectNum = new int[index]; + System.arraycopy(temp, 0, perfectNum, 0, index); + return perfectNum; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder stb = new StringBuilder(); + for(int i = 0; i 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ +public class Struts { + + public static View runAction(String actionName, Map parameters) { + View view = new View(); + //0.读取xml文件 + Document doc = createDOC("struts.xml"); + Class actionClass= queryClass(actionName, doc); + //1.实例化对象调用set方法 + Set paramNames = parameters.keySet(); //取出调用方法所用参数名称 + Iterator iter = paramNames.iterator(); + Object ob = null; + try { + ob = actionClass.newInstance(); + while(iter.hasNext()){ + String temp = iter.next(); + String methodName = "set"+temp.replaceFirst( temp.substring(0,1),temp.substring(0,1).toUpperCase());//方法名称 + String methodParam = parameters.get(temp); //方法参数 + Method me= actionClass.getMethod(methodName,String.class); + me.invoke(ob,methodParam); + } + //2.调用execute反方法取出返回值 + String actionMethod = (String)actionClass.getMethod("execute").invoke(ob); + //3.调用所有的get,并保存返回值 + Map map = new HashMap(); + Method[] methods = actionClass.getMethods(); + for(Method method : methods){ + String methodName = method.getName(); + if(methodName.substring(0,3).equals("get")){ + Object value = method.invoke(ob); + String key = methodName.substring(3,methodName.length()).toLowerCase(); + map.put(key, value); + } + } + view.setParameters(map);//将数据保存到view中 + //4.设置返回结果视图 + String jsp = queryResult(actionName,doc,actionMethod); + view.setJsp(jsp); + } catch (Exception e) { + e.printStackTrace(); + } + + return view; + } + private static String queryResult(String actionName,Document doc,String actionMethod){ + String reView = null; + Element el = queryActionElement(actionName,doc);//查找action元素 + List resultEl = el.elements("result"); + for(Element rel : resultEl){ + Attribute att = rel.attribute("name"); + if(att.getValue().equals(actionMethod)){ + reView = rel.getText(); + } + } + return reView; + } + //查找对应的action元素 + private static Element queryActionElement(String actionName, Document doc){ + Element root = doc.getRootElement(); + Element actionElement = null; + List list = root.elements("action"); + for(Element el : list){ + Attribute att = el.attribute("name"); + if(att.getValue().equals(actionName)){ + actionElement = el; + } + } + return actionElement; + + } + //查找action类 + private static Class queryClass(String actionName, Document doc) { + Element el = queryActionElement(actionName,doc);//查找action元素 + Attribute att = el.attribute("class"); + String className = att.getValue(); + + Class actionClass = null; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return actionClass; + } + //获取document对象 + private static Document createDOC(String fileName){ + + //使用dom4j的读取xml文件 + SAXReader sr = new SAXReader(); + URL fileUrl = Struts.class.getResource(fileName); + Document doc = null; + try { + doc = sr.read(fileUrl); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return doc; + } + +} diff --git a/group22/1193590951/githubitem/src/com/github/mrwengq/sec/StrutsTest.java b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/StrutsTest.java new file mode 100644 index 0000000000..2b848ce991 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/StrutsTest.java @@ -0,0 +1,43 @@ +package com.github.mrwengq.sec; + +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/group22/1193590951/githubitem/src/com/github/mrwengq/sec/View.java b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/View.java new file mode 100644 index 0000000000..1c09f0ba33 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/View.java @@ -0,0 +1,23 @@ +package com.github.mrwengq.sec; + +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/group22/1193590951/githubitem/src/com/github/mrwengq/sec/struts.xml b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/struts.xml new file mode 100644 index 0000000000..404aa778e1 --- /dev/null +++ b/group22/1193590951/githubitem/src/com/github/mrwengq/sec/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group22/1258890344/.gitignore b/group22/1258890344/.gitignore new file mode 100644 index 0000000000..ea7fd75f1f --- /dev/null +++ b/group22/1258890344/.gitignore @@ -0,0 +1,48 @@ +/bin/ +# Class files +*.class + +# Package Files +*.jar +*.war +*.ear + +# Virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Ignore web-site project +*web-site/ + +# Temporary files +.DS_STORE +*.log + +# Maven related +/*/target/ +target + +# Netbeans related +nb-configuration.xml +nbactions.xml +nbproject + +# Eclipse related + +.settings +*.classpath +*.project + +# IntelliJ related +.idea +*.iml +*.ipr +*.iws + +# Jrebel related +rebel.xml +rebel-remote.xml + +# design model +*.eab + +.idea/workspace.xml \ No newline at end of file diff --git a/group22/1258890344/src/com/coderising/array/ArrayUtil.java b/group22/1258890344/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..773b66ffb7 --- /dev/null +++ b/group22/1258890344/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,209 @@ +package com.coderising.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 void reverseArray(int[] origin){ + int length=origin.length; + int value=0; + for(int i=0;i<(length/2);i++){ + value=origin[i]; + origin[i]=origin[length-1-i]; + origin[length-1-i]=value; + + } + } + + /** + * 现在有如下的一个数组: 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[] newArray = new int[length]; + int j=0; + for(int i=0;iarray2[j]){ + for(int k=length1;k>i;k--){ + array3[k]=array3[k-1]; + } + array3[i]=array2[j]; + j++; + if(j1){ + array[0]=1; + array[1]=1; + for(int i=2;i>1;i++){ + array[i]=array[i-1]+array[i-2]; + if(array[i]>=max){ + array[i]=0; + return array; + } + } + } + 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 k=0; + if(max==2){ + array[0]=2; + } + for(int i=3;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字段中。 + + */ + View view=new View(); + try { + SAXReader reader=new SAXReader(); + Document doc=reader.read("./src/com/coderising/litestruts/struts.xml"); + Element root=doc.getRootElement(); + List list=root.elements();//将所有元素放到集合中 + List> listMap=getElements(list); + int size=listmap.size(); + listMap.remove(size-1); + System.out.println(listMap.toString()); + + String pathName=""; + int index=0; + String name=parameters.get("name"); + String password=parameters.get("password"); + + Map parameter=new HashMap<>(); + + for(int i=0;i> listmap = new ArrayList>(); + private static Map map=new LinkedHashMap(); + private static List> getElements(List list){ + + for(Iterator itera1=list.iterator();itera1.hasNext();){ + String key=""; + String value=""; + //获取action、result + Element element=itera1.next(); + if(element.getName()=="action"){ + map = new LinkedHashMap(); + } + if(element.getText().trim()!=null){ + value=element.getText(); + } + List attributes=element.attributes(); + + + //获取action、result里的属性名和值 + for(Iterator itera2=attributes.iterator();itera2.hasNext();){ + Attribute attr=itera2.next(); + + if(attr.getName().equals("name")){ + key=attr.getValue(); + } + if(attr.getName().equals("class")){ + value=attr.getValue(); + + } + if(!key.trim().isEmpty()&&!value.trim().isEmpty()){ + map.put(key, value); + } + } + + List subList=element.elements(); + //递归action的的子元素们 + if(subList.size()!=0){ + getElements(subList); + } + } + listmap.add(map); + return listmap; + } +} diff --git a/group22/1258890344/src/com/coderising/litestruts/StrutsTest.java b/group22/1258890344/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..ff10b5dd33 --- /dev/null +++ b/group22/1258890344/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,47 @@ +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); + System.out.println( view.getJsp()); + System.out.println( view.getParameters().get("message")); + +// 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); + +// System.out.println( view.getJsp()); +// System.out.println( view.getParameters().get("message")); + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group22/1258890344/src/com/coderising/litestruts/View.java b/group22/1258890344/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group22/1258890344/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/group22/1258890344/src/com/coderising/litestruts/struts.xml b/group22/1258890344/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..171848ecd1 --- /dev/null +++ b/group22/1258890344/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/group22/1258890344/src/com/coding/basic/ArrayList.java b/group22/1258890344/src/com/coding/basic/ArrayList.java new file mode 100644 index 0000000000..b61c1d833c --- /dev/null +++ b/group22/1258890344/src/com/coding/basic/ArrayList.java @@ -0,0 +1,76 @@ +package com.coding.basic; + +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(this.size==elementData.length){ + elementData=Arrays.copyOf(elementData, size+1); + elementData[size]=o; + }else{ + elementData[size]=o; + } + size++; + + } + public void add(int index, Object o){ + if(index<0||index>=this.size){ + throw new ArrayIndexOutOfBoundsException("数组越界异常"); + }else{ + if(indexelementData.length){ + throw new ArrayIndexOutOfBoundsException("数组越界异常"); + } + return elementData[index]; + + } + + public Object remove(int index){ + if(index<0||index>=elementData.length){ + throw new ArrayIndexOutOfBoundsException("数组越界异常"); + }else{ + Object deletedElement=elementData[index]; + if(index7->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/group22/1258890344/src/com/coding/basic/List.java b/group22/1258890344/src/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/group22/1258890344/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/group22/1258890344/src/com/coding/basic/Queue.java b/group22/1258890344/src/com/coding/basic/Queue.java new file mode 100644 index 0000000000..1c76d442ef --- /dev/null +++ b/group22/1258890344/src/com/coding/basic/Queue.java @@ -0,0 +1,27 @@ +package com.coding.basic; + +public class Queue { + private LinkedList list=new LinkedList(); + private int size=0; + public void enQueue(Object o){ + list.addLast(o); + size++; + } + + public Object deQueue(){ + Object o= list.removeFirst(); + size--; + return o; + } + + public boolean isEmpty(){ + if(size==0){ + return true; + } + return false; + } + + public int size(){ + return size; + } +} diff --git a/group22/1258890344/src/com/coding/basic/Stack.java b/group22/1258890344/src/com/coding/basic/Stack.java new file mode 100644 index 0000000000..8b2ee6c7e2 --- /dev/null +++ b/group22/1258890344/src/com/coding/basic/Stack.java @@ -0,0 +1,27 @@ +package com.coding.basic; + +public class Stack { + private ArrayList list = new ArrayList(); + private int size=0; + public void push(Object o){ + list.add(o); + size++; + } + + public Object pop(){ + Object o=list.remove(size-1); + size--; + return o; + } + + public Object peek(){ + Object o=list.get(size-1); + return o; + } + public boolean isEmpty(){ + return size==0?true:false; + } + public int size(){ + return size; + } +} diff --git a/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtil.java b/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..a9e5e8bde0 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtil.java @@ -0,0 +1,239 @@ +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){ + if(checkArrayIsNull(origin)){ + return; + } + int size = origin.length; + for (int i = 0; i < size/2; i++) { + int swap = origin[i]; + origin[i] = origin[size - 1 - i]; + origin[size - 1 - i] = swap; + } + } + + /** + * 现在有如下的一个数组: 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(checkArrayIsNull(oldArray)){ + return null; + } + int[] swap = new int [oldArray.length]; + int size = 0; + for (int i = 0; i < oldArray.length; i++) { + if(oldArray[i] == 0){ + continue; + } + swap[size] = oldArray[i]; + ++size; + + } + int[] newArray = new int[size]; + System.arraycopy(swap, 0, newArray, 0, size); + 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){ + if(checkArrayIsNull(array1) && checkArrayIsNull(array2)){ + return null; + } + int[] swap = new int[array1.length + array2.length]; + int index1 = 0,index2 = 0,size = 0; + while(index1 < array1.length && index2 < array2.length){ + if(array1[index1] == array2[index2]){ + swap[size++] = array1[index1]; + ++index1; + ++index2; + }else if(array1[index1] < array2[index2]){ + if(size > 0 && swap[size-1] == array1[index1]){ + ++index1; + continue; + } + swap[size++] = array1[index1++]; + }else{ + if(size > 0 && swap[size-1] == array2[index2]){ + ++index2; + continue; + } + swap[size++] = array2[index2++]; + } + + } + while(index1 < array1.length){ + swap[size++] = array1[index1]; + ++index1; + } + while(index2 < array2.length){ + swap[size++] = array2[index2]; + ++index2; + } + int[] newArray = new int [size]; + System.arraycopy(swap, 0, newArray, 0, size); + 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){ + if(checkArrayIsNull(oldArray)){ + return null; + } + int length = oldArray.length; + int[] newArray = new int [length + size]; + System.arraycopy(oldArray, 0, newArray, 0, 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){ + if(max <= 0){ + return null; + } + if(max == 1){ + return new int[0]; + } + int array[] = null; + if(max < 20 ){ + array = new int [max]; + }else{ + array =new int [max/2]; + } + array[0] = array[1] = 1; + int index = 1; + while(array[index-1] + array[index] < max){ + array[index+1] = array[index-1] + array[index]; + ++index; + } + int[] newArray = new int [index+1]; + System.arraycopy(array, 0, newArray, 0, index+1); + 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; + } + int init = 2; + int size = 0; + int array[] = new int[max]; + boolean flag = true; + while(init < max){ + flag = true; + for (int i = 2; i < init; i++) { + if(init % i == 0){ + flag = false; + break; + } + } + if(flag){ + array[size++] = init; + } + ++init; + } + int[] newArray = new int [size]; + System.arraycopy(array, 0, newArray, 0, size); + return newArray; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + if(max < 6){ + return null; + } + int array[] = new int[max]; + int init = 6; + int size = 0,sum = 0; + while(init < max){ + sum = 0; + for (int i = 1; i <= init/2; i++) { + if(init % i == 0){ + sum += i; + } + } + if(sum == init){ + array[size++] = init; + } + ++init; + } + int[] newArray = new int [size]; + System.arraycopy(array, 0, newArray, 0, size); + return newArray; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + if(checkArrayIsNull(array) || seperator == null){ + return null; + } + StringBuilder stringBuilder = new StringBuilder(); + int size = array.length; + for (int i = 0; i < size; i++) { + if(i != size - 1){ + stringBuilder.append(array[i]).append(seperator); + continue; + } + stringBuilder.append(array[i]); + } + return stringBuilder.toString(); + } + + private boolean checkArrayIsNull(int[] array){ + if(array == null){ + return true; + } + return false; + } + +} diff --git a/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtilTest.java b/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtilTest.java new file mode 100644 index 0000000000..d2f4d2b668 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/com/coderising/array/ArrayUtilTest.java @@ -0,0 +1,84 @@ +package com.coderising.array; + +import java.util.Arrays; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ArrayUtilTest { + + public static ArrayUtil arrayUtil; + + @BeforeClass + public static void arrayUtil() throws Exception { + arrayUtil = new ArrayUtil(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Test + public void reverseArrayTest() { + int[] array = {1,2,3,4,5,6,7}; + int[] swapAfter = {7,6,5,4,3,2,1}; + arrayUtil.reverseArray(array); + Assert.assertEquals(Arrays.toString(swapAfter), Arrays.toString(array)); + + } + + @Test + public void removeZeroTest(){ + int[] array = {0,1,0,0,2,3,4,5,6,0,0,7,0}; + int[] array2 = {1,2,3,4,5,6,7}; + int[] removeZero = arrayUtil.removeZero(array); + Assert.assertEquals(Arrays.toString(array2), Arrays.toString(removeZero)); + } + + @Test + public void mergeTest(){ + int[] array1 = {1,2,3,4,5}; + int[] array2 = {4,5,7,8,13,15}; + int[] array3 = {1,2,3,4,5,7,8,13,15}; + int[] merge = arrayUtil.merge(array1, array2); + Assert.assertEquals(Arrays.toString(array3), Arrays.toString(merge)); + } + + @Test + public void growTest(){ + int[] array = {1,2,3,4,5,6,7}; + int[] array2 = {1,2,3,4,5,6,7,0,0,0}; + int[] grow = arrayUtil.grow( array, 3); + Assert.assertEquals(Arrays.toString(array2), Arrays.toString(grow)); + } + + @Test + public void fibonacciTest(){ + int[] fibonacci = arrayUtil.fibonacci(1000); + int[] array2 = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987}; + Assert.assertEquals(Arrays.toString(array2), Arrays.toString(fibonacci)); + } + + @Test + public void getPrimesTest(){ + int[] primes = arrayUtil.getPrimes(20); + int[] array2 = {2, 3, 5, 7, 11, 13, 17, 19}; + Assert.assertEquals(Arrays.toString(array2), Arrays.toString(primes)); + } + + @Test + public void getPerfectNumbersTest(){ + int[] perfectNumbers = arrayUtil.getPerfectNumbers(1000); + int[] array2 = {6, 28, 496}; + Assert.assertEquals(Arrays.toString(array2), Arrays.toString(perfectNumbers)); + } + + @Test + public void joinTest(){ + int[] join = {2,4,5,6}; + String join2 = arrayUtil.join(join, "-"); + Assert.assertEquals("2-4-5-6", join2); + } +} diff --git a/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/LoginAction.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..1005f35a29 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/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/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/Struts.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..d231ca1634 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,154 @@ +package com.coderising.litestruts; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.InputStream; +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.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字段中。 + + */ + View view = null; + SAXReader reader = new SAXReader(); + InputStream resourceAsStream = Struts.class.getResourceAsStream("struts.xml"); + try { + Document document = reader.read(resourceAsStream); + Element rootElement = document.getRootElement(); + + Element element = findElement(rootElement, actionName); + if(element == null){ + throw new RuntimeException("指定节点不存在"); + } + //子节点数据信息 + Map elementData = getElementData(element); + Class forName = Class.forName(element.attribute("class").getValue()); + Object classInstance = forName.newInstance(); + PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(forName).getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + String name = propertyDescriptor.getName(); + Method readMethod = propertyDescriptor.getWriteMethod(); + if(parameters != null && parameters.size() > 0 && parameters.containsKey(name) && readMethod != null){ + readMethod.setAccessible(true); + readMethod.invoke(classInstance, parameters.get(name)); + } + } + Method method = forName.getDeclaredMethod("execute"); + method.setAccessible(true); + Object o = method.invoke(classInstance); + Map viewMap = new HashMap(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + String name = propertyDescriptor.getName(); + Method readMethod = propertyDescriptor.getReadMethod(); + if(readMethod != null && !"class".equals(name)){ + viewMap.put(name, readMethod.invoke(classInstance)); + } + } + view = new View(); + view.setParameters(viewMap); + if(elementData != null && elementData.size() > 0 && elementData.containsKey(o)){ + view.setJsp(elementData.get(o)); + }else{ + view.setJsp(null); + } + } catch (DocumentException e) { + e.printStackTrace(); + } 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(); + } catch (IntrospectionException e) { + e.printStackTrace(); + } + return view; + } + + /** + * 根据名称获取指定节点 + * @param rootElement 根节点 + * @param actionName action名称 + * @return + */ + private static Element findElement(Element rootElement,String actionName){ + @SuppressWarnings("unchecked") + List elements = rootElement.elements("action"); + for (Element element : elements) { + Attribute name = element.attribute("name"); + if(name == null){ + return null; + } + String value = name.getValue(); + if(value == null || !value.equals(actionName)){ + continue; + } + Attribute actionClass = element.attribute("class"); + if(actionClass == null || actionClass.getValue() == null){ + return null; + } + return element; + } + return null; + } + + /** + * 获取action下的result节点信息 + * @param element action节点 + * @return + */ + private static Map getElementData(Element element){ + Map map = null; + @SuppressWarnings("unchecked") + List elements = element.elements("result"); + for (Element elementSub : elements) { + if(map == null){ + map = new HashMap(); + } + Attribute attribute = elementSub.attribute("name"); + if(attribute!=null){ + map.put(attribute.getValue(), elementSub.getTextTrim()); + } + } + return map; + } +} diff --git a/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/StrutsTest.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..a44c1878ac --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/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/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/View.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..0194c681f6 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/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/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/struts.xml b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..4c6eeabbd4 --- /dev/null +++ b/group22/1335499238/coding2017/src/main/java/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/group22/1335499238/week01/src/basic/ArrayList.java b/group22/1335499238/week01/src/basic/ArrayList.java new file mode 100644 index 0000000000..64b3045312 --- /dev/null +++ b/group22/1335499238/week01/src/basic/ArrayList.java @@ -0,0 +1,123 @@ +package basic; + +import java.util.Arrays; + +public class ArrayList implements List{ + + private int size; + + private Object[] elementData = {}; + + public ArrayList(){ + this(16); + } + + public ArrayList(int capacity){ + if(capacity > 0){ + elementData = new Object[capacity]; + }else if(capacity == 0){ + + }else{ + new IllegalArgumentException("initsize:"+capacity); + } + } + + @Override + public void add(Object o) { + ensureCapacity(elementData.length + 1); + elementData[size++] = o; + } + + @Override + public void add(int index, Object o) { + checkIndex(index); + ensureCapacity(size + 1); + System.arraycopy(elementData, index, elementData, index+1, size - index); + elementData[index] = o; + size++; + } + + @Override + public Object get(int index) { + checkIndex(index); + return elementData[index]; + } + + @Override + public Object remove(int index) { + checkIndex(index); + Object removeparam = elementData[index]; + int numMoved = size - index - 1; + if(numMoved > 0){ + System.arraycopy(elementData, index+1, elementData, index, numMoved); + } + elementData[--size] = null; //置空末尾元素 + return removeparam; + } + + @Override + public int size() { + return size; + } + + /** + * 检查是否越界 + * @param index + */ + public void checkIndex(int index){ + if(index > size || index < 0){ + throw new IndexOutOfBoundsException("current:"+index+" size:"+size); + } + } + + /** + * 判断当前容量是否足够 + * @param minCapacity + */ + private void ensureCapacity(int minCapacity){ + if(minCapacity > elementData.length){ + grow(minCapacity); + } + } + + /** + * 扩容 + * @param minCapacity + */ + private void grow(int minCapacity){ + Object [] target = new Object [minCapacity+10]; + System.arraycopy(elementData, 0, target, 0, elementData.length); + elementData = target; + } + + public Iterator iterator() { + return new ArrayListIterator(); + } + + private class ArrayListIterator implements Iterator{ + + private int current = 0; + + @Override + public boolean hasNext() { + return current < size; + } + + @Override + public Object next() { + int i = current; + if(current >= size){ + throw new IndexOutOfBoundsException("current:"+current+" size:"+size); + } + current++; + return elementData[i]; + } + + } + + @Override + public String toString() { + return Arrays.toString(Arrays.copyOf(elementData, size)); + } + +} diff --git a/group22/1335499238/week01/src/basic/BinaryTreeNode.java b/group22/1335499238/week01/src/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..92ca37ef18 --- /dev/null +++ b/group22/1335499238/week01/src/basic/BinaryTreeNode.java @@ -0,0 +1,81 @@ +package basic; + +public class BinaryTreeNode >{ + + + private T data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public BinaryTreeNode(T o){ + this.data = o; + this.left = null; + this.right = null; + } + + public Object 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 BinaryTreeNode insert(T o){ + BinaryTreeNode current = this; + BinaryTreeNode addTreeNode = new BinaryTreeNode<>(o); + while(true){ + //如果传入的值比但前节点的值小 + if(o.compareTo(current.data) < 0){ + if(current.left != null){ + current = current.left; + }else { + current.left = addTreeNode; + break; + } + }else{ + if(current.right != null){ + current = current.right; + }else{ + current.right =addTreeNode; + break; + } + } + } + return addTreeNode; + } + + public LinkedList prevOrder(BinaryTreeNode binaryTreeNode){ + LinkedList linkedList = new LinkedList(); + preOrder(binaryTreeNode, linkedList); + return linkedList; + } + + private void preOrder(BinaryTreeNode binaryTreeNode,LinkedList linkedList){ + if(binaryTreeNode.left != null){ + preOrder(binaryTreeNode.left, linkedList); + + } + linkedList.add(binaryTreeNode.data); + if(binaryTreeNode.right != null){ + preOrder(binaryTreeNode.right, linkedList); + } + } + +} diff --git a/group22/1335499238/week01/src/basic/Iterator.java b/group22/1335499238/week01/src/basic/Iterator.java new file mode 100644 index 0000000000..576b1a4af4 --- /dev/null +++ b/group22/1335499238/week01/src/basic/Iterator.java @@ -0,0 +1,9 @@ +package basic; + +public interface Iterator { + + public boolean hasNext(); + + public Object next(); + +} diff --git a/group22/1335499238/week01/src/basic/LinkedList.java b/group22/1335499238/week01/src/basic/LinkedList.java new file mode 100644 index 0000000000..9af1471bfb --- /dev/null +++ b/group22/1335499238/week01/src/basic/LinkedList.java @@ -0,0 +1,206 @@ +package basic; + + +public class LinkedList implements List{ + + private Node head; + + private int size; + + @Override + public void add(Object o) { + addLast(o); + } + + @Override + public void add(int index, Object o) { + checkIndex(index); + Node current = findByIndex(index); + Node newNode = new Node(o, current); + if(index == 0){ + head = newNode; + }else{ + Node perv = findByIndex(index-1); + perv.next = newNode; + } + size++; + } + + @Override + public Object get(int index) { + checkIndex(index); + return findByIndex(index).data; + } + + @Override + public Object remove(int index) { + Node remove = null; + checkIndex(index); + Node next = findByIndex(index+1); + if(index == 0){ + remove = head; + if(next == null){ + head = null; + }else { + head = next; + } + }else{ + Node perv = findByIndex(index-1); + remove = perv.next; + perv.next = next; + } + size--; + return remove.data; + } + + @Override + public int size() { + return size; + } + + public void addFirst(Object o){ + head = new Node(o, head); + size++; + } + + public void addLast(Object o){ + Node nextNode = new Node(o, null); + if(head == null){ + head = nextNode; + }else{ + Node lastNode = findByIndex(size-1); + lastNode.next = nextNode; + } + size++; + } + + public Object removeFirst(){ + return remove(0); + } + + public Object removeLast(){ + return remove(size-1); + } + + public Iterator iterator(){ + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator{ + + int current = 0; + + @Override + public boolean hasNext() { + return current < size; + } + + @Override + public Object next() { + Node findByIndex = findByIndex(current); + if(current >= size){ + throw new IndexOutOfBoundsException("current:"+current+" size:"+size); + } + current++; + return findByIndex.data; + } + + } + + private static class Node{ + Object data; + Node next; + + Node(Object data, Node next){ + this.data = data; + this.next = next; + } + } + + private Node findByIndex(int index){ + Node lastNode = head; + for (int i = 0; i < index; i++) { + lastNode = lastNode.next; + } + return lastNode; + } + + private void checkIndex(int index){ + if(index > size || index < 0){ + throw new IndexOutOfBoundsException("current:"+index+" size:"+size); + } + } + /** + * 把该链表逆置 + * 例如链表为 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){ + + } + /** + * 假定当前链表和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; + } + +} diff --git a/group22/1335499238/week01/src/basic/List.java b/group22/1335499238/week01/src/basic/List.java new file mode 100644 index 0000000000..82612a4487 --- /dev/null +++ b/group22/1335499238/week01/src/basic/List.java @@ -0,0 +1,15 @@ +package 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/group22/1335499238/week01/src/basic/Queue.java b/group22/1335499238/week01/src/basic/Queue.java new file mode 100644 index 0000000000..81eb073387 --- /dev/null +++ b/group22/1335499238/week01/src/basic/Queue.java @@ -0,0 +1,21 @@ +package basic; + +public class Queue { + + private LinkedList linkList = new LinkedList(); + + public void enQueue(Object o){ + linkList.add(o); + } + + public Object deQueue(){ + return linkList.removeFirst(); + } + + public boolean isEmpty(){ + return linkList.size() == 0; + } + public int size(){ + return linkList.size(); + } +} diff --git a/group22/1335499238/week01/src/basic/Stack.java b/group22/1335499238/week01/src/basic/Stack.java new file mode 100644 index 0000000000..38baac269a --- /dev/null +++ b/group22/1335499238/week01/src/basic/Stack.java @@ -0,0 +1,29 @@ +package basic; + +public class Stack { + + private ArrayList elementData = new ArrayList(); + + private int size = 0; + + public void push(Object o){ + elementData.add(o); + size++; + } + + public Object pop(){ + return elementData.remove(size-1); + } + + public Object peek(){ + return elementData.get(size-1); + } + + public boolean isEmpty(){ + return size == 0; + } + + public int size(){ + return size; + } +} diff --git a/group22/1335499238/week01/src/test/ArrayListTest.java b/group22/1335499238/week01/src/test/ArrayListTest.java new file mode 100644 index 0000000000..bf54c307dc --- /dev/null +++ b/group22/1335499238/week01/src/test/ArrayListTest.java @@ -0,0 +1,40 @@ +package test; + + +import org.junit.Assert; +import org.junit.Test; + +import basic.ArrayList; +import basic.Iterator; + +public class ArrayListTest { + + @Test + public void test01(){ + ArrayList arrayList = new ArrayList(); + arrayList.add("612"); + arrayList.add("1"); + arrayList.add("2"); + arrayList.add("5"); + arrayList.add("6"); + Assert.assertEquals("[612, 1, 2, 5, 6]", arrayList.toString()); + + Object remove = arrayList.remove(2); + Assert.assertEquals("2", remove); + + arrayList.add(2, "13"); + Assert.assertEquals("[612, 1, 13, 5, 6]", arrayList.toString()); + + Object object = arrayList.get(2); + Assert.assertEquals("13", object); + + Assert.assertEquals(5, arrayList.size()); + + Iterator iterator = arrayList.iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next()+" "); + + } + } + +} diff --git a/group22/1335499238/week01/src/test/BinaryTreeNodeTest.java b/group22/1335499238/week01/src/test/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..18f3b7897b --- /dev/null +++ b/group22/1335499238/week01/src/test/BinaryTreeNodeTest.java @@ -0,0 +1,26 @@ +package test; + +import org.junit.Test; + +import basic.BinaryTreeNode; +import basic.Iterator; +import basic.LinkedList; + +public class BinaryTreeNodeTest { + + @Test + public void test01(){ + BinaryTreeNode binaryTreeNode = new BinaryTreeNode(20); + binaryTreeNode.insert(5); + binaryTreeNode.insert(40); + binaryTreeNode.insert(30); + binaryTreeNode.insert(10); + binaryTreeNode.insert(15); + LinkedList prevOrder = binaryTreeNode.prevOrder(binaryTreeNode); + Iterator iterator = prevOrder.iterator(); + while(iterator.hasNext()){ + System.out.print(iterator.next()+" "); + } + } + +} diff --git a/group22/1335499238/week01/src/test/LinkedListTest.java b/group22/1335499238/week01/src/test/LinkedListTest.java new file mode 100644 index 0000000000..8a7fa7f444 --- /dev/null +++ b/group22/1335499238/week01/src/test/LinkedListTest.java @@ -0,0 +1,52 @@ +package test; + +import org.junit.Assert; +import org.junit.Test; + +import basic.Iterator; +import basic.LinkedList; + +public class LinkedListTest { + + @Test + public void test01(){ + LinkedList linkedList = new LinkedList(); + linkedList.add(122); + linkedList.add("qwe"); + linkedList.add(133); + iterator(linkedList); + + linkedList.add(1, "asd"); + iterator(linkedList); + + linkedList.addFirst("1"); + iterator(linkedList); + + linkedList.addLast("zxc"); + iterator(linkedList); + + Object remove = linkedList.remove(2); + Assert.assertEquals("asd", remove); + + Object removeFirst = linkedList.removeFirst(); + Assert.assertEquals("1", removeFirst); + + Object removeLast = linkedList.removeLast(); + Assert.assertEquals("zxc", removeLast); + + int size = linkedList.size(); + Assert.assertEquals(3, size); + + + + } + + public static void iterator(LinkedList linkedList){ + Iterator iterator = linkedList.iterator(); + while(iterator.hasNext()){ + System.out.print(iterator.next()+" "); + } + System.out.println(); + } + +} diff --git a/group22/1335499238/week01/src/test/QueueTest.java b/group22/1335499238/week01/src/test/QueueTest.java new file mode 100644 index 0000000000..61d4eb91c9 --- /dev/null +++ b/group22/1335499238/week01/src/test/QueueTest.java @@ -0,0 +1,30 @@ +package test; + +import org.junit.Assert; +import org.junit.Test; + +import basic.Queue; + +public class QueueTest { + + @Test + public void test01(){ + + Queue queue = new Queue(); + boolean empty1 = queue.isEmpty(); + Assert.assertEquals(true, empty1); + queue.enQueue("111"); + queue.enQueue("222"); + queue.enQueue("333"); + Object deQueue = queue.deQueue(); + Assert.assertEquals("111", deQueue); + + boolean empty2 = queue.isEmpty(); + Assert.assertEquals(false, empty2); + + int size = queue.size(); + Assert.assertEquals(2, size); + } + + +} diff --git a/group22/1335499238/week01/src/test/StackTest.java b/group22/1335499238/week01/src/test/StackTest.java new file mode 100644 index 0000000000..95c440b8af --- /dev/null +++ b/group22/1335499238/week01/src/test/StackTest.java @@ -0,0 +1,32 @@ +package test; + +import org.junit.Assert; +import org.junit.Test; + +import basic.Stack; + +public class StackTest { + + @Test + public void test1(){ + Stack stack = new Stack(); + + Assert.assertEquals(true, stack.isEmpty()); + + stack.push(123); + stack.push("qwe"); + stack.push(456); + + Assert.assertEquals(false, stack.isEmpty()); + + int size = stack.size(); + Assert.assertEquals(3, size); + + Object peek = stack.peek(); + Assert.assertEquals(456, peek); + + Object pop = stack.pop(); + Assert.assertEquals(456, pop); + } + +} diff --git a/group22/17457741/src/ArrayList.java b/group22/17457741/src/ArrayList.java new file mode 100644 index 0000000000..45b583d13c --- /dev/null +++ b/group22/17457741/src/ArrayList.java @@ -0,0 +1,110 @@ +import java.util.Iterator; +import java.util.NoSuchElementException; + +public class ArrayList implements Iterable{ + private static final int CAPACITY = 5; + + private int size; + + private T [] items; + + public ArrayList(){doClear();} + + public void clear(){ + doClear(); + } + + private void doClear(){ + this.size=0;ensureCapacity(CAPACITY); + } + + public int size(){ + return size; + } + + public boolean isEmpty(){ + return size==0; + } + + public void trimToSize(){ + ensureCapacity(size()); + } + + public T get( int a){ + return items[a]; + } + + public T set(int a,T b){ + T old = items[a]; + items[a]=b; + return old; + } + + public void ensureCapacity(int newCapacity){ + if(newCapacitya;i--){ + items[i]=items[i-1]; + } + items[a]=b; + size++; + } + + public T remove(int a){ + T removedItem=items[a]; + for(int i=a;i iterator() { + // TODO Auto-generated method stub + return new ArrayListIterator(); + } + + private class ArrayListIterator implements Iterator{ + + private int current =0; + + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return current implements Iterable{ + private Nodebegin; + private Nodeend; + private int size; + private int modCount=0; + + public LinkedList(){ + doClear(); + } + public void clear(){ + doClear(); + } + private void doClear(){ + begin=new Node(null,null,null); + end=new Node(null,begin,null); + begin.next=end; + } + + public int size(){ + return size; + } + public boolean isEmpty(){ + return size==0; + } + + public boolean add( T x){ + add(size(),x); + return true; + } + public void add(int a,T x){ + addBefore(getNode(a,0,size()),x); + } + + public T get(int a){ + return getNode(a).data; + } + public T set(int a,T newVal){ + Nodep=getNode(a); + T old=p.data; + p.data=newVal; + return old; + } + + public T remove(int a){ + return remove(getNode(a)); + } + + private void addBefore(Nodep,T x){ + Node newNode=new Node<>(x,p.prev,p); + newNode.prev.next=newNode; + p.prev=newNode; + size++; + modCount--; + } + + private T remove(Nodep){ + p.next.prev=p.prev; + p.prev.next=p.next; + size--; + modCount++; + + return p.data; + } + + private NodegetNode(int a){ + return getNode(a,0,size()-1); + } + + private NodegetNode(int a,int lower,int upper){ + Nodep; + + if(aupper) + throw new IndexOutOfBoundsException(); + if(aa;i--) + p=p.prev; + } + return p; + } + @Override + public Iterator iterator() { + // TODO Auto-generated method stub + return new LinkedListIterator(); + } + private class LinkedListIterator implements Iterator{ + private Node current=begin.next; + private int expectedModCount=modCount; + private boolean toRemove=false; + + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return current!=end; + } + @Override + public T next() { + // TODO Auto-generated method stub + if(modCount!=expectedModCount) + throw new java.util.ConcurrentModificationException(); + if(!toRemove) + throw new IllegalStateException(); + + T nextItem=current.data; + current=current.next; + toRemove=true; + return nextItem; + } + + public void remove(){ + if(modCount!=expectedModCount) + throw new java.util.ConcurrentModificationException(); + if(!toRemove) + throw new IllegalStateException(); + + LinkedList.this.remove(current.prev); + expectedModCount++; + toRemove=false; + } + } + + private static class Node{ + + public T data; + public Node prev; + public Node next; + + public Node(T d, Node p,Node n) { + // TODO Auto-generated constructor stub + data=d;prev=p;next=n; + } + + } + +} + diff --git a/group22/17457741/src/Queue.java b/group22/17457741/src/Queue.java new file mode 100644 index 0000000000..b98d8e2043 --- /dev/null +++ b/group22/17457741/src/Queue.java @@ -0,0 +1,29 @@ + + +public class Queue { + + private ArrayList list = new ArrayList(); + + public void enQueue(Object o) { + list.add(o); + } + + public Object deQueue() { + final int size = list.size(); + if (0 == size) + return null; + Object o = list.remove(size); + return o; + } + + public boolean isEmpty() { + return list.isEmpty(); + } + + public int size() { + return list.size(); + } + +} + + diff --git a/group22/17457741/src/Stack.java b/group22/17457741/src/Stack.java new file mode 100644 index 0000000000..12f870566f --- /dev/null +++ b/group22/17457741/src/Stack.java @@ -0,0 +1,33 @@ + + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + + elementData.add(o); + } + + public Object peek(){ + return elementData.get(0); + } + + public Object pop(){ + Object a = null; + if(elementData.size() > 0) { + + a = elementData.get(elementData.size() - 1); + elementData.remove(elementData.size() - 1); + } + return a; + } + + public boolean isEmpty(){ + return elementData.size() == 0; + } + + public int size(){ + return elementData.size(); + } + +} diff --git a/group22/17457741/src/address.txt b/group22/17457741/src/address.txt new file mode 100644 index 0000000000..975ea2b26d --- /dev/null +++ b/group22/17457741/src/address.txt @@ -0,0 +1 @@ + http://www.cnblogs.com/xxp17457741/p/6504673.html \ No newline at end of file diff --git a/group22/17457741/src/adress2.txt b/group22/17457741/src/adress2.txt new file mode 100644 index 0000000000..b728064ab8 --- /dev/null +++ b/group22/17457741/src/adress2.txt @@ -0,0 +1 @@ +http://www.cnblogs.com/xxp17457741/p/6568230.html \ No newline at end of file diff --git a/group22/17457741/src/secondwork/ArrayUtil.java b/group22/17457741/src/secondwork/ArrayUtil.java new file mode 100644 index 0000000000..29f1bf31c8 --- /dev/null +++ b/group22/17457741/src/secondwork/ArrayUtil.java @@ -0,0 +1,157 @@ +package secondwork; + + +import java.util.Arrays; + +import org.junit.Test; + +public class ArrayUtil { + public void reverseArray (int [] origin){ + int le =origin.length; + int []changedArray=Arrays.copyOf(origin, le); + for (int i=0;i parameters) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, SecurityException { + Map actionMap = StrutsParser.doParse(); + StrutsAction action = actionMap.get(actionName); + + if (action == null) { + System.out.println("couldn't get action: " + actionName + ", return"); + return null; + } + + try { + // 通过反射, 创建实例对象 + Class actionClass = Class.forName(action.getActionClassName()); + Object actionObj = actionClass.newInstance(); + + // 调用 parameters 中的 set 方法 + for (Map.Entry parameterEntry : parameters.entrySet()) { + Method[] methods = actionClass.getMethods(); + for (Method method : methods) { + if (method.getName().equalsIgnoreCase("set" + parameterEntry.getKey())) { + method.invoke(actionObj, parameterEntry.getValue()); + } + } + } + + Method executeMethod = actionClass.getMethod("execute"); + Object executeResult = executeMethod.invoke(actionObj); + + // 根据 execute 方法的结果, 获取 xml 配置的 jsp 页面 + String jsp = action.getAttributes().get(Objects.toString(executeResult)); + + + Map actionFieldMap = new HashMap<>(); + Field[] actionFields = actionClass.getDeclaredFields(); + for (Field actionFiled : actionFields) { + Method[] methods = actionClass.getMethods(); + for (Method method : methods) { + if (method.getName().equalsIgnoreCase("get" + actionFiled.getName())) { + method.invoke(actionObj); + actionFieldMap.put(actionFiled.getName(), Objects.toString(method.invoke(actionObj))); + } + } + } + + View view = new View(); + view.setParameters(actionFieldMap); + view.setJsp(jsp); + return view; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/group22/17457741/src/secondwork/StrutsAction.java b/group22/17457741/src/secondwork/StrutsAction.java new file mode 100644 index 0000000000..fe30f54363 --- /dev/null +++ b/group22/17457741/src/secondwork/StrutsAction.java @@ -0,0 +1,24 @@ +package secondwork; + +import java.util.Map; + +public class StrutsAction { + private String actionClassName; + private Map attributes; + + public String getActionClassName() { + return actionClassName; + } + + public void setActionClassName(String actionClassName) { + this.actionClassName = actionClassName; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } +} diff --git a/group22/17457741/src/secondwork/StrutsParser.java b/group22/17457741/src/secondwork/StrutsParser.java new file mode 100644 index 0000000000..c3342872f7 --- /dev/null +++ b/group22/17457741/src/secondwork/StrutsParser.java @@ -0,0 +1,77 @@ +package secondwork; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.Element; + +import com.sun.xml.internal.txw2.Document; + + + +public class StrutsParser { + + private static final String STRUTS_XML = "struts.xml"; + + public static void main(String[] args) { + Map strutsActions = doParse(); + System.out.println(strutsActions.size()); + } + + public static Map doParse() { + Map resultMap = new HashMap<>(); + + SAXReader reader = new SAXReader(); + InputStream in = getStrutsInputStream(); + try { + Document document = reader.read(in); + Element rootElement = document.getRootElement(); + + + List elementActions = rootElement.elements(); + for (Element elementAction : elementActions) { + StrutsAction action = new StrutsAction(); + + + resultMap.put(elementAction.attribute("name").getValue(), action); + + // parse "class" attribute from action element + action.setActionClassName(elementAction.attribute("class").getValue()); + + // parse sub elements in action element + List elements = elementAction.elements(); + Map map = new HashMap<>(); + for (Element element : elements) { + map.put(element.attribute("name").getValue(), element.getStringValue()); + } + action.setAttributes(map); + } + + return resultMap; + } catch (DocumentException e) { + throw new IllegalStateException("failed to parse " + STRUTS_XML, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private static InputStream getStrutsInputStream() { + StrutsParser.class.getPackage().getName(); + InputStream in = StrutsParser.class.getClassLoader() + .getResourceAsStream("org/korben/coderising/litestruts/util/" + STRUTS_XML); + if (in == null) { + throw new IllegalStateException(STRUTS_XML + " doesn't exist"); + } + + return in; + } +} diff --git a/group22/17457741/src/secondwork/TestStrust.java b/group22/17457741/src/secondwork/TestStrust.java new file mode 100644 index 0000000000..7629899c2b --- /dev/null +++ b/group22/17457741/src/secondwork/TestStrust.java @@ -0,0 +1,40 @@ +package secondwork; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + +public class TestStrust { + @Test + public void testLoginActionSuccess() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, SecurityException { + + 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 IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, SecurityException { + 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/group22/17457741/src/secondwork/View.java b/group22/17457741/src/secondwork/View.java new file mode 100644 index 0000000000..44e4754edb --- /dev/null +++ b/group22/17457741/src/secondwork/View.java @@ -0,0 +1,26 @@ +package secondwork; + +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/group22/17457741/src/secondwork/adress2.txt b/group22/17457741/src/secondwork/adress2.txt new file mode 100644 index 0000000000..b728064ab8 --- /dev/null +++ b/group22/17457741/src/secondwork/adress2.txt @@ -0,0 +1 @@ +http://www.cnblogs.com/xxp17457741/p/6568230.html \ No newline at end of file diff --git a/group22/17457741/src/secondwork/struts.xml b/group22/17457741/src/secondwork/struts.xml new file mode 100644 index 0000000000..9c2574460d --- /dev/null +++ b/group22/17457741/src/secondwork/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/group22/2622819383/Task1/.gitignore b/group22/2622819383/Task1/.gitignore new file mode 100644 index 0000000000..5241a7220a --- /dev/null +++ b/group22/2622819383/Task1/.gitignore @@ -0,0 +1 @@ +*.class \ No newline at end of file diff --git a/group22/2622819383/Task1/ArrayList.java b/group22/2622819383/Task1/ArrayList.java new file mode 100644 index 0000000000..d438fba17d --- /dev/null +++ b/group22/2622819383/Task1/ArrayList.java @@ -0,0 +1,162 @@ +//代码参考自《数据结构与算法分析》 +public class ArrayList implements List { + + private int size; + + private int capacity; + + private static final int DEFAULT_CAPACITY = 10; + + private Object[] elementData; + + //add()时用于在必要时刻扩充底层数组容量 + private void expand() { + if (size < capacity) return;//尚未满员,不必扩容 + if (capacity < DEFAULT_CAPACITY) capacity = DEFAULT_CAPACITY;//不低于最小容量 + + Object[] oldElem = elementData; + elementData = new Object[capacity <<= 1]; + for (int i = 0; i < size; i++) + elementData[i] = oldElem[i]; + } + + //remove()时用于在必要时刻缩小底层数组容量 + private void shrink() { + if (capacity < DEFAULT_CAPACITY << 1) return;//不致收缩至DEFAULT_CAPACITY以下 + if (capacity >> 2 < size) return; //以25%为界 + + Object[] oldElem = elementData; elementData = new Object[capacity >>= 1]; + for (int i = 0; i < size; i++) + elementData[i] = oldElem[i]; + } + + public ArrayList() { + clear(); + } + + + public void clear() { + size = 0; + elementData = new Object[capacity = DEFAULT_CAPACITY]; + } + + public int size() { + return size; + } + + public int capacity() { //用于测试shrink()&expand() + return capacity; + } + + public boolean isEmpty() { + return size == 0; + } + + public void add(Object o){ + add(size(), o); + } + + public void add(int index, Object o){ + if (index < 0 || size < index) + throw new IndexOutOfBoundsException(); + + expand(); + for (int i = size; i > index; i--) + elementData[i] = elementData[i - 1]; + elementData[index] = o; + size++; + } + + public Object get(int index){ + if (index < 0 || size <= index) + throw new IndexOutOfBoundsException(); + + return elementData[index]; + } + + public Object remove(int index){ + if (index < 0 || size <= index) + throw new IndexOutOfBoundsException(); + + Object removed = elementData[index]; + for (int i = index; i < size - 1; i++) + elementData[i] = elementData[i + 1]; + size--; + shrink(); + return removed; + } + + + + public Iterator iterator(){ + return new ArrayListIterator(); + } + + private class ArrayListIterator implements Iterator { + private int current; + + public boolean hasNext() { + return current != size; + } + + public Object next() { + if (!hasNext()) + throw new java.util.NoSuchElementException(); + + return elementData[current++]; + } + } + + + //以下方法便于测试 + + public ArrayList(Object ...args) { + this(); + for (Object o : args) + add(o); + } + + public void add(Object ...args) { + for (Object o : args) + add(o); + } + + public void removeElems(int ...args) { + for (int i : args) + remove(i); + } + public static void showElements(ArrayList list) { + System.out.print("当前list中元素:"); + Iterator iter = list.iterator(); + while (iter.hasNext()) + System.out.print(iter.next() + " "); + System.out.println(); + } + + public static void test(ArrayList list) { + System.out.println("--------基本方法测试---------"); + System.out.println("当前list.isEmpty(): " + list.isEmpty()); + System.out.println("当前list.size(): " + list.size()); + System.out.println("当前list.capacity(): " + list.capacity()); + showElements(list); + } + + public static void main(String[] args) { + ArrayList list = new ArrayList(1, 2, 3, 4, 5); + test(list); + list.add(6, 7, 8, 9, 10); + test(list); + list.add(3, 11); + list.get(3); + test(list); + list.remove(3); + test(list); + list.add(11,12,13,14,15,16,17,18,19,20,21,22,23,24); + test(list); + + list.removeElems(1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1); + test(list); + + + } +} diff --git a/group22/2622819383/Task1/BinaryTreeNode.java b/group22/2622819383/Task1/BinaryTreeNode.java new file mode 100644 index 0000000000..8c2b4492d2 --- /dev/null +++ b/group22/2622819383/Task1/BinaryTreeNode.java @@ -0,0 +1,54 @@ +//οԡݽṹ㷨 +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; + } + + private BinaryTreeNode parrent; + private BinaryTreeNode hot; //ʾsearch(Object o)صнڵĸ + + public BinaryTreeNode(Object o, BinaryTreeNode p) { + data = o; + parrent = p; + } + //vΪĶвҹؼoеĽڵ㣨ʵڵûڵģ + public static BinaryTreeNode search(BinaryTreeNode v, Object o, BinaryTreeNode hot) { + int vData = (int)v.getData(); + int searched = (int)o; + if (v == null || vData == searched) return v; + + hot = v; + return search(searched < vData ? v.getLeft() : v.getRight(), o, hot); + } + + public BinaryTreeNode insert(Object o){ + BinaryTreeNode node = search(this, o, this.parrent); + if (node != null) return node; + + node = new BinaryTreeNode(o, hot); + if ((int)o < (int)hot.getData()) hot.setLeft(node); + else hot.setRight(node); + return node; + } + +} diff --git a/group22/2622819383/Task1/Iterator.java b/group22/2622819383/Task1/Iterator.java new file mode 100644 index 0000000000..f390e63f3a --- /dev/null +++ b/group22/2622819383/Task1/Iterator.java @@ -0,0 +1,5 @@ +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group22/2622819383/Task1/LinkedList.java b/group22/2622819383/Task1/LinkedList.java new file mode 100644 index 0000000000..81c1db409c --- /dev/null +++ b/group22/2622819383/Task1/LinkedList.java @@ -0,0 +1,203 @@ +//οԡݽṹ㷨 +public class LinkedList implements List { + + private Node header; + + private Node trailer; + + private int theSize; + + public LinkedList() { + header = new Node(null, null, null); + trailer = new Node(null, header, null); + header.succ = trailer; + theSize = 0; + } + + public void add(Object o) { + add(size(), o); + } + + public void add(int index , Object o) { + if (index < 0 || theSize < index) throw new IndexOutOfBoundsException(); + + Node p = header; + while (0 < index--) p = p.succ(); + p.insertAsSucc(o); + theSize++; + } + + public Object get(int index) { + if (index < 0 || theSize <= index) throw new IndexOutOfBoundsException(); + + Node p = header.succ(); + while (0 < index--) p = p.succ(); + return p.data(); + } + + public Object remove(int index) { + if (0 < index || theSize <= index) throw new IndexOutOfBoundsException(); + + Node p = header.succ(); + while (0 < index--) p = p.succ(); + Object removed = p.data(); + p.pred().succ = p.succ(); + p.succ().pred = p.pred(); + theSize--; + return removed; + } + + public int size() { + return theSize; + } + + public void addFirst(Object o) { + header.insertAsSucc(o); + } + + public void addLast(Object o) { + trailer.insertAsPred(o); + } + + public Object removeFirst() { + return remove(0); + } + + public Object removeLast() { + return remove(theSize - 1); + } + + public Iterator iterator() { + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator { + private Node current = header.succ(); + + public boolean hasNext() { + return current != trailer; + } + + public Object next() { + if (!hasNext()) throw new java.util.NoSuchElementException(); + Object item = current.data(); + current = current.succ(); + return item; + } + } + + private static class Node { + //predsuccԣpred()succ()Nodeڵ + private Object data; + private Node pred; + private Node succ; + + public Node(Object d, Node p, Node s) { + data = d; + pred = p; + succ = s; + } + + public Object data() { + return data; + } + + public Node succ() { + return succ; + } + + public Node pred() { + return pred; + } + + //ǰڵ㣬ز½ڵ + public Node insertAsPred(Object data) { + Node p = new Node(data, pred, this); + pred = pred().succ = p; + return p; + } + + //̽ڵ㣬ز½ڵ + public Node insertAsSucc(Object data) { + Node p = new Node(data, this, succ); + succ = succ().pred = p; + return p; + } + } + + /** + * Ѹ + * Ϊ 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 Ԫ עi0ʼ + * @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/group22/2622819383/Task1/List.java b/group22/2622819383/Task1/List.java new file mode 100644 index 0000000000..c8f6da95a8 --- /dev/null +++ b/group22/2622819383/Task1/List.java @@ -0,0 +1,7 @@ +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/group22/2622819383/Task1/Queue.java b/group22/2622819383/Task1/Queue.java new file mode 100644 index 0000000000..fa916cb089 --- /dev/null +++ b/group22/2622819383/Task1/Queue.java @@ -0,0 +1,19 @@ +public class Queue { + private LinkedList elementData = new LinkedList(); + + public void enQueue(Object o){ + elementData.addLast(o); + } + + public Object deQueue(){ + return elementData.removeFirst(); + } + + public boolean isEmpty(){ + return size() == 0; + } + + public int size(){ + return elementData.size(); + } +} diff --git a/group22/2622819383/Task1/Stack.java b/group22/2622819383/Task1/Stack.java new file mode 100644 index 0000000000..3072c65370 --- /dev/null +++ b/group22/2622819383/Task1/Stack.java @@ -0,0 +1,23 @@ +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + return elementData.remove(size() - 1); + } + + public Object peek(){ + return elementData.get(size() - 1); + } + + public boolean isEmpty(){ + return size() == 0; + } + + public int size(){ + return elementData.size(); + } +} diff --git a/group22/573535234/RemoteSystemsTempFiles/.project b/group22/573535234/RemoteSystemsTempFiles/.project new file mode 100644 index 0000000000..5447a64fa9 --- /dev/null +++ b/group22/573535234/RemoteSystemsTempFiles/.project @@ -0,0 +1,12 @@ + + + RemoteSystemsTempFiles + + + + + + + org.eclipse.rse.ui.remoteSystemsTempNature + + diff --git a/group22/573535234/githubTutorial/.classpath b/group22/573535234/githubTutorial/.classpath new file mode 100644 index 0000000000..fb565a588d --- /dev/null +++ b/group22/573535234/githubTutorial/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/group22/573535234/githubTutorial/.gitignore b/group22/573535234/githubTutorial/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group22/573535234/githubTutorial/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group22/573535234/githubTutorial/.project b/group22/573535234/githubTutorial/.project new file mode 100644 index 0000000000..ad0a1d9490 --- /dev/null +++ b/group22/573535234/githubTutorial/.project @@ -0,0 +1,17 @@ + + + githubTutorial + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group22/573535234/githubTutorial/.settings/org.eclipse.jdt.core.prefs b/group22/573535234/githubTutorial/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..7341ab1683 --- /dev/null +++ b/group22/573535234/githubTutorial/.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/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/ArrayList.java b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/ArrayList.java new file mode 100644 index 0000000000..feeaaa2d94 --- /dev/null +++ b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/ArrayList.java @@ -0,0 +1,76 @@ +package com.lys.coding.week2.basic; + +import java.util.Arrays; + +public class ArrayList implements List{ + + private int size = 0; + + private Object[] elementData = new Object[100]; + + @Override + public void add(Object o) { + //ȼǷ,Ҫ + if(size>=elementData.length){ + int newLength = elementData.length*3/2+1; + Arrays.copyOf(elementData, newLength); + } + // + elementData[size+1]=o; + //sizeһ + size++; + } + + @Override + public void add(int index, Object o) { + //ȼǷ,Ҫ + if(size>=elementData.length){ + int newLength = elementData.length*3/2+1; + Arrays.copyOf(elementData, newLength); + } + if(index!=size-1){ + //ѵǰindexŲ + System.arraycopy(elementData, index, elementData, index+1, size-index); + } + //indexλ÷ + elementData[index]=o; + //sizeһ + size++; + } + + @Override + public Object get(int index) { + //indexǷǷ + if(index>=size){ + throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); + }else if(index<0){ + throw new IllegalArgumentException("Index: "+index+",<0!"); + } + return elementData[index]; + } + + @Override + public Object remove(int index) { + Object o = elementData[index]; + //indexǷǷ + if(index>=size){ + throw new IndexOutOfBoundsException("Index: "+index+",Size:"+size); + }else if(index<0){ + throw new IllegalArgumentException("Index: "+index+",<0!"); + } + if(size!=index+1){ + //ѵǰindexǰŲ + System.arraycopy(elementData, index+1, elementData, index, size-index-1); + } + elementData[size]=null; + //sizeһ + size--; + return o; + } + + @Override + public int size() { + return size; + } + +} diff --git a/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/LinkedList.java b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/LinkedList.java new file mode 100644 index 0000000000..f46f218e60 --- /dev/null +++ b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/LinkedList.java @@ -0,0 +1,164 @@ +package com.lys.coding.week2.basic; + +import java.util.Iterator; + +public class LinkedList implements List{ + + private Node head; + + public void add(Object o){ + if(head==null){ + head = new Node(); + head.data = o; + }else{ + Node nodes = head; + while(nodes.next!=null){ + nodes = nodes.next; + } + nodes.next = new Node(); + nodes.next.data = o; + } + } + public void add(int index , Object o){ + int len = size(); + if(len7->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 Ԫ עi0ʼ + * @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; + } +} diff --git a/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/List.java b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/List.java new file mode 100644 index 0000000000..a92e7cabf5 --- /dev/null +++ b/group22/573535234/githubTutorial/src/com/lys/coding/week2/basic/List.java @@ -0,0 +1,9 @@ +package com.lys.coding.week2.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/group22/592864103/ArrayList.java b/group22/592864103/ArrayList.java new file mode 100644 index 0000000000..cf716f728e --- /dev/null +++ b/group22/592864103/ArrayList.java @@ -0,0 +1,123 @@ +import java.util.Arrays; +//import java.util.Objects; + +public class ArrayList implements List { + + //private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o) { + if (o == null) { + System.out.println("传入对象不能为空!"); + return; + } else { + if (size() == elementData.length) { + Object[] elementData2 = Arrays.copyOf(elementData, ((int) (elementData.length * 1.2))); + elementData2[size()] = o; + elementData = elementData2; + } else { + elementData[size()] = o; + } + } + } + + public void add(int index, Object o) { + if (o == null) { + System.out.println("传入对象不能为空!"); + return; + } + if ((index > size())) { + System.out.println("超出数组长度!"); + return; + } else { + if (size() == elementData.length) { + Object[] elementData2 = Arrays.copyOf(elementData, ((int) (elementData.length * 1.2))); + rightShift(elementData2, index); + elementData2[index] = o; + elementData = elementData2; + return; + } else { + rightShift(elementData, index); + elementData[size()] = o; + return; + } + } + } + + public Object get(int index) { + if ((index > size() - 1)) { + System.out.println("超出数组长度!"); + return null; + } else { + return elementData[index]; + } + } + + public Object remove(int index) { + if (index > size() - 1) { + System.out.println("超出数组长度!"); + return null; + }else{ + Object o = elementData[index]; + elementData[index]=null; + leftShift(elementData,index); + return o; + } + } + + public int size() { + int n; + for (n = 0; n < elementData.length; n++) { + if (elementData[n] == null) { + break; + } + } + return n; + } + + + public Iterator iterator() { + return new ArrayListIterator(this); + } + + public class ArrayListIterator implements Iterator{ + ArrayList list = new ArrayList(); + int pos = 0; + ArrayListIterator(ArrayList list){ + this.list = list; + } + + @Override + public boolean hasNext() { + if (pos index; k--) { + o[k] = o[k - 1]; + } + } + + public void leftShift(Object[] o, int index) { + for (int k = index; k < size(); k++) { + o[k] = o[k + 1]; + } + } +} diff --git a/group22/592864103/BinaryTreeNode.java b/group22/592864103/BinaryTreeNode.java new file mode 100644 index 0000000000..b6aa3100b6 --- /dev/null +++ b/group22/592864103/BinaryTreeNode.java @@ -0,0 +1,59 @@ +public class BinaryTreeNode { + + private Integer data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public Integer getData() { + return data; + } + public void setData(Integer 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(Integer o){ + if(o>getData()){ + if(this.right==null){ + BinaryTreeNode node = new BinaryTreeNode(); + node.data = o; + node.left = null; + node.right = null; + this.right = node; + return node; + }else{ + getRight(); + insert(o); + return null; + } + }else if(o size())) { + System.out.println("超出数组长度!"); + return; + } else if (index == 0) { + Node temp = new Node(); + temp.data = head.data; + temp.next = head.next; + head.data = o; + head.next = temp; + } else { + Node cursor = head; + Node temp = new Node(); + for (int i = 0; i < index - 1; i++) { + cursor = cursor.next; + } + temp.data = o; + temp.next = cursor.next; + cursor.next = temp; + } + } + + public Object get(int index) { + if ((index > size())) { + System.out.println("超出数组长度!"); + return null; + } else { + Node cursor = head; + for (int i = 0; i < index; i++) { + cursor = cursor.next; + } + return cursor; + } + } + + public Object remove(int index) { + if ((index > size())) { + System.out.println("超出数组长度!"); + return null; + } else if (index == 0) { + Node temp = new Node(); + temp.data = head.data; + temp.next = head.next; + head = head.next; + return temp; + } else { + Node cursor = head; + for (int i = 0; i < index - 1; i++) { + cursor = cursor.next; + } + Node temp = new Node(); + Node target = cursor.next; + temp.data = target.data; + temp.next = target.next; + cursor.next = target.next; + return temp; + } + } + + + public int size() { + Node cursor = head; + int size = 0; + while (cursor != null) { + cursor = cursor.next; + size++; + } + return size; + } + + public void addFirst(Object o) { + Node temp = new Node(); + temp.data = head.data; + temp.next = head.next; + head.data = o; + head.next = temp; + } + + public void addLast(Object o) { + if (o == null) { + System.out.println("传入对象不能为空!"); + } else if (head == null) { + head.data = o; + head.next = null; + } else { + Node cursor = head; + for (int i = 0; i < size(); i++) { + cursor = cursor.next; + } + cursor.data = o; + cursor.next = null; + } + } + + public Object removeFirst() { + Node temp = new Node(); + temp.data = head.data; + temp.next = head.next; + head = head.next; + return temp; + } + + public Object removeLast() { + Node temp = new Node(); + Node cursor = head; + for (int i = 0; i < size() - 2; i++) { + cursor = cursor.next; + } + Node last = cursor.next; + temp.data = last.data; + temp.next = null; + cursor.next = null; + return temp; + } + + public Iterator iterator() { + return new LinkedListIterator(this); + } + public class LinkedListIterator implements Iterator{ + int pos = 0; + LinkedList list = new LinkedList(); + LinkedListIterator(LinkedList list){ + this.list = list; + } + @Override + public boolean hasNext() { + if (pos7->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/group22/592864103/List.java b/group22/592864103/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/group22/592864103/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/group22/592864103/Queue.java b/group22/592864103/Queue.java new file mode 100644 index 0000000000..764d265c1e --- /dev/null +++ b/group22/592864103/Queue.java @@ -0,0 +1,34 @@ +public class Queue { + + LinkedList elementData = new LinkedList(); + + public void enQueue(Object o) { + if (o == null) { + System.out.println("传入对象不能为空"); + } else { + elementData.add(o); + } + } + + public Object deQueue() { + if (isEmpty()==true){ + System.out.println("该队列为空队列!"); + return null; + }else{ + Object o = elementData.removeFirst(); + return o; + } + } + + public boolean isEmpty() { + if (elementData.size()==0){ + return true; + }else { + return false; + } + } + + public int size() { + return elementData.size(); + } +} diff --git a/liuxin/src/com/coding/basic/Stack.java b/group22/592864103/Stack.java similarity index 93% rename from liuxin/src/com/coding/basic/Stack.java rename to group22/592864103/Stack.java index 4bfe28057f..a5a04de76d 100644 --- a/liuxin/src/com/coding/basic/Stack.java +++ b/group22/592864103/Stack.java @@ -1,22 +1,22 @@ -package com.coding.basic; - -public class Stack { - private ArrayList elementData = new ArrayList(); - - public void push(Object o){ - } - - public Object pop(){ - return null; - } - - public Object peek(){ - return null; - } - public boolean isEmpty(){ - return false; - } - public int size(){ - return -1; - } -} +package com.coding.basic; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/group22/627559964/src/com/coderising/array/ArrayUtil.java b/group22/627559964/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..e97b5f7a7c --- /dev/null +++ b/group22/627559964/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,198 @@ +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 static int[] reverseArray(int[] origin){ + int size = origin.length; + int[] result = new int[size]; + for (int i = 0; i < size; i++) { + int temp = origin[size-1-i]; + result[i] = temp; + } + return result; + } + + /** + * 现在有如下的一个数组: 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; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] == 0) { + countZero ++; + } + } + int[] result = new int[size - countZero]; + for (int i = 0, j = 0; i < size; i++) { + int temp = oldArray[i]; + if (temp != 0) { + result[j] = temp; + j ++; + } + } + 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 static int[] merge(int[] array1, int[] array2){ + int[] result = new int[array1.length + array2.length]; + System.arraycopy(array1, 0, result, 0, array1.length); + System.arraycopy(array2, 0, result, array1.length, array2.length); + Arrays.sort(result); + return result; + } + /** + * 把一个已经存满数据的数组 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[] 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 static int[] fibonacci(int max){ + List resultList = new ArrayList(); + int temp = 0; + for (int i = 1; i <= max; i++) { + temp = getFibo(i); + if (temp > max) { + break; + } + resultList.add(temp); + } + return getArrayFromList(resultList); + } + /** + * 计算斐波那契数列 + * @param i + * @return + */ + private static int getFibo(int i) { + if (i == 1 || i == 2) { + return 1; + } else { + return getFibo(i - 1) + getFibo(i - 2); + } + } + + /** + * 通过list过得int[]数组 + * @param list + * @return + */ + private static int[] getArrayFromList(List list) { + int[] result = new int[list.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = list.get(i); + } + return result; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public static int[] getPrimes(int max){ + List result = new ArrayList(); + boolean isPrime = true; + for (int i = 2; i < max; i++) { + for (int j = 2; j < i; j++) { + if (i % j == 0) { + isPrime = false; + break; + } + } + if (isPrime) { + result.add(i); + } + isPrime = true; + } + + return getArrayFromList(result); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public static int[] getPerfectNumbers(int max){ + List result = new ArrayList(); + for (int i = 1; i <= max; i++) { + int temp = 0; + for (int j = 1; j < i/2 + 1; j++) { + if(i%j == 0) { + temp += j; + } + } + if (temp == i) { + result.add(i); + } + } + return getArrayFromList(result); + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public static String join(int[] array, String seperator){ + List result = Arrays.asList(array); + int size = array.length; + StringBuffer rs = new StringBuffer(); + for (int i = 0; i < size; i++) { + rs.append(result.get(0)[i]); + if (i != size-1) { + rs.append(seperator); + } + } + return rs.toString(); + } + + +} \ No newline at end of file diff --git a/group22/627559964/src/com/coderising/litestruts/LoginAction.java b/group22/627559964/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..eef38d702e --- /dev/null +++ b/group22/627559964/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/group22/627559964/src/com/coderising/litestruts/Struts.java b/group22/627559964/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..5eef643ff1 --- /dev/null +++ b/group22/627559964/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,112 @@ +package com.coderising.litestruts; + +import java.io.File; +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; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) throws Exception { + + /* + + 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字段中?? + + */ + + //创建view对象 + View view = new View(); + + //读取xml文件的Document对象 + SAXReader reader = new SAXReader(); + Document document = reader.read(new File("src/com/coderising/litestruts/struts.xml")); + + //获取根节? + Element root = document.getRootElement(); + //根节点不是struts?,结束方法 + if (!root.getName().equals("struts")) { + return null; + } + //获取action匹配actionName的节? + List children = root.elements("action"); + Element targetElement = null; + for (Element element : children) { + System.out.println("name:" + element.attributeValue("name")); + System.out.println("class" + element.attributeValue("class")); + if (element.attributeValue("name").equals(actionName)) { + targetElement = element; + } + } + //没有name参数?,结束方法 + if (targetElement.attributeCount() <= 0) { + return null; + } + + Class clazz = Class.forName(targetElement.attributeValue("class")); + Object obj = clazz.newInstance(); + Method setName = clazz.getDeclaredMethod("setName", String.class); + Method setPassword = clazz.getDeclaredMethod("setPassword", String.class); + Method execute = clazz.getDeclaredMethod("execute"); + setName.invoke(obj, parameters.get("name")); + setPassword.invoke(obj, parameters.get("password")); + String remsg = (String) execute.invoke(obj); + System.out.println("结果?" + remsg); + + Map parameter = new HashMap(); + Method[] gets = clazz.getDeclaredMethods(); + for (Method method : gets) { + String methodName = method.getName(); + String name = methodName.substring(0,3); + if (name.equals("get")) { + Method getxxx = clazz.getDeclaredMethod(methodName); + String xxx = methodName.substring(3, methodName.length()).toLowerCase(); + String temp = (String) getxxx.invoke(obj); + parameter.put(xxx, temp); + } + } + List targetChilren = targetElement.elements(); + for (Element element : targetChilren) { + String resultName = element.attributeValue("name"); + System.out.println(resultName); + if ("success".equalsIgnoreCase(resultName)) { + view.setJsp(element.getText()); + continue; + } + if ("fail".equalsIgnoreCase(resultName)) { + view.setJsp(element.getText()); + continue; + } + } + view.setParameters(parameter); + + return view; + } + +} diff --git a/group22/627559964/src/com/coderising/litestruts/StrutsTest.java b/group22/627559964/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..37d6840016 --- /dev/null +++ b/group22/627559964/src/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,62 @@ +package com.coderising.litestruts; + +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() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = null; + try { + view = Struts.runAction(actionName,params); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + 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 = null; + try { + view = Struts.runAction(actionName,params); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(view.getJsp()); + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group22/627559964/src/com/coderising/litestruts/View.java b/group22/627559964/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group22/627559964/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/group22/627559964/src/com/coderising/litestruts/struts.xml b/group22/627559964/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..171848ecd1 --- /dev/null +++ b/group22/627559964/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/group22/627559964/src/com/coding/basic/ArrayList.java b/group22/627559964/src/com/coding/basic/ArrayList.java new file mode 100644 index 0000000000..59d055dfa7 --- /dev/null +++ b/group22/627559964/src/com/coding/basic/ArrayList.java @@ -0,0 +1,165 @@ +package com.coding.basic; + +import java.util.Arrays; + +/** + * ԶArrayList + * + * @author xiongrui233 + * + */ +public class ArrayList implements List { + + // list + private int size = 0; + + // listԪؼ + private Object[] elementData = new Object[10]; + + /** + * ϲ + * + * @param arrays1 + * @param arrays2 + * @return Object[] + */ + private Object[] concat(Object[] arrays1, Object[] arrays2) { + Object[] newArrays = new Object[arrays1.length + arrays2.length]; + System.arraycopy(arrays1, 0, newArrays, 0, arrays1.length); + System.arraycopy(arrays2, 0, newArrays, arrays1.length, arrays2.length); + return newArrays; + } + + /** + * ָ + * + * @param arrays + * @param from + * @param index + * @return Object[] + */ + private Object[] subArrays(Object[] arrays, int from, int index) { + Object[] tempArrays = new Object[index - from]; + for (int i = from, j = 0; i < index; i++, j++) { + tempArrays[j] = arrays[i]; + } + return tempArrays; + } + + /** + * ̬list + * Ϊ:newSize = oldSize * 1.5 + * + * @param oldSize + */ + private void grow(int oldSize) { + elementData = Arrays.copyOf(elementData, oldSize + oldSize / 2); + } + + /** + * ڲԪʱ,listǷ㹻 + * + * @param newSize + */ + private void checkSize(int newSize) { + int oldSize = elementData.length; + if (newSize > oldSize) { + grow(oldSize); + } + } + + /** + * Ԫ + * + * @param Object + */ + public void add(Object o) { + checkSize(size + 1); + elementData[size++] = o; + } + + /** + * Ԫ + * + * @param index + * @param Object + */ + public void add(int index, Object o) { + checkSize(size + 1); + Object[] arrays1 = subArrays(elementData, 0, index); + Object[] arrays2 = subArrays(elementData, index, elementData.length); + + arrays1 = Arrays.copyOf(arrays1, arrays1.length + 1); + arrays1[index] = o; + size++; + elementData = concat(arrays1, arrays2); + } + + /** + * ñΪindexԪ + * + * @param int + * @return Object + */ + public Object get(int index) { + return elementData[index]; + } + + /** + * ɾΪindexԪ + * + * @param int + * @return Object + */ + public Object remove(int index) { + Object[] arrays1 = subArrays(elementData, 0, index); + Object[] arrays2 = subArrays(elementData, index + 1, elementData.length); + Object obj = elementData[index]; + + size--; + elementData = concat(arrays1, arrays2); + return obj; + } + + /** + * list + * + * @return int + */ + public int size() { + return size; + } + + /** + * д + * + * @return IteratorImpl + */ + public Iterator iterator() { + + class IteratorImpl implements Iterator { + + private int point = 0; + + @Override + public boolean hasNext() { + if (elementData[point] != null) { + return true; + } + return false; + } + + @Override + public Object next() { + return elementData[point++]; + } + + } + return new IteratorImpl(); + } + + @Override + public String toString() { + return Arrays.toString(Arrays.copyOf(elementData, size)); + } +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/BinaryTreeNode.java b/group22/627559964/src/com/coding/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..9c416d3ad3 --- /dev/null +++ b/group22/627559964/src/com/coding/basic/BinaryTreeNode.java @@ -0,0 +1,65 @@ +package com.coding.basic; + +/** + * Զ + * + * @author xiongrui233 + * + */ +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; + } + + /** + * Ԫ + * @param o + * @return BinaryTreeNode + */ + public BinaryTreeNode insert(Object o) { + BinaryTreeNode node = null; + if (this.data == null) { + this.data = o; + node = this; + } else { + if (this.left.data == null) { + this.left.data = o; + node = this.left; + } + if (this.right.data == null) { + this.right.data = o; + node = this.right; + } + } + return node; + } + +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/Iterator.java b/group22/627559964/src/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..c4c1725d21 --- /dev/null +++ b/group22/627559964/src/com/coding/basic/Iterator.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface Iterator { + + public boolean hasNext(); + + public Object next(); + +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/LinkedList.java b/group22/627559964/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..dcae1fb835 --- /dev/null +++ b/group22/627559964/src/com/coding/basic/LinkedList.java @@ -0,0 +1,320 @@ +package com.coding.basic; + +/** + * ԶLinkList + * + * @author xiongrui233 + * + */ +public class LinkedList implements List { + + /** + * ڵṹ + * + * @author xiongrui233 + * + */ + private static class Node { + Object data; + Node next; + } + + // ڵ + private Node head = new Node(); + + private int size = 0; + + public LinkedList() { + head.next = head; + } + + /** + * Ԫ + * + * @param o + */ + public void add(Object o) { + addLast(o); + } + + /** + * Ԫ + * + * @param index + * @param o + */ + public void add(int index, Object o) { + if (index < 0 || index > size) { + throw new ArrayIndexOutOfBoundsException(); + } + Node node = head; + Node temp = new Node(); + for (int i = 0; i < index; i++) { + node = node.next; + } + temp.data = o; + if (index == size -1) { + node.next = temp; + temp.next = head; + } else { + temp.next = node.next; + node.next = temp; + } + size ++; + } + + /** + * ȡԪ + * + * @param index + */ + public Object get(int index) { + Node node = head; + for (int i = 0; i <= index; i++) { + node = node.next; + } + return node.data; + } + + /** + * ɾԪ + * + * @param index + */ + public Object remove(int index) { + if (index < 0 || index > size) { + throw new ArrayIndexOutOfBoundsException(); + } + Node node = head; + Node temp = new Node(); + for (int i = 0; i <= index - 1; i++) { + node = node.next; + } + if (index == size -1) { + temp = node.next; + node.next = head; + } else { + temp = node.next; + node.next = node.next.next; + } + size --; + return temp.data; + } + + /** + * LinkedListĴС + * + * @return size + */ + public int size() { + return size; + } + + /** + * LinkedListһλԪ + * + * @param o + */ + public void addFirst(Object o) { + add(0, o); + } + + /** + * LinkedListԪ + * @param o + */ + public void addLast(Object o) { + Node node = head; + Node temp = new Node(); + for (int i = 0; i < size; i++) { + node = node.next; + } + temp.data = o; + node.next = temp; + size ++; + } + + /** + * ƳһλԪ + * + * @return obj + */ + public Object removeFirst() { + return remove(0); + } + + /** + * ƳһλԪ + * + * @return obj + */ + public Object removeLast() { + return remove(size - 1); + } + + /** + * ʵIteratorӿ + * + * @return Iterator + */ + public Iterator iterator() { + + class IteratorImpl implements Iterator { + + private Node node = head.next; + + private Object temp = null; + + @Override + public boolean hasNext() { + if (node != null && node.data != null) { + temp = node.data; + node = node.next; + return true; + } + return false; + } + + @Override + public Object next() { + return temp; + } + + } + return new IteratorImpl(); + } + + /** + * Ѹ Ϊ 3->7->10 , úΪ 10->7->3 + */ + public LinkedList reverse() { + LinkedList lis = new LinkedList(); + for (int i = this.size - 1; i >= 0; i--) { + lis.add(this.get(i)); + } + return lis; + } + + /** + * ɾһǰ벿 磺list = 2->5->7->8 , ɾԺֵΪ 7->8 list = 2->5->7->8->10 + * ,ɾԺֵΪ7,8,10 + */ + public void removeFirstHalf() { + int mid = size/2; + for (int i = 0; i < mid; i++) { + remove(0); + } + } + + /** + * ӵiԪؿʼ ɾlength Ԫ עi0ʼ + * + * @param i + * @param length + */ + public void remove(int i, int length) { + if (i > length) { + throw new IllegalArgumentException(); + } + if (i < 0 || i > size) { + throw new ArrayIndexOutOfBoundsException(); + } + for (int j = i; j <= length; j++) { + remove(i); + } + } + + /** + * ٶǰ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 (this.size < (Integer)list.get(list.size - 1)) { + throw new IllegalArgumentException(); + } + int[] elements = new int[list.size]; + for (int i = 0; i < elements.length; i++) { + elements[i] = (Integer) this.get((Integer)list.get(i)); + } + return elements; + } + + /** + * ֪еԪֵУԵ洢ṹ ӵǰɾlistгֵԪ + * + * @param list + */ + + public void subtract(LinkedList list) { + Iterator it = list.iterator(); + while (it.hasNext()) { + Object obj = it.next(); + for (int i = 0; i < this.size; i++) { + if (obj.equals(this.get(i))) { + this.remove(i); + } + } + } + } + + /** + * ֪ǰеԪֵУԵ洢ṹ ɾֵͬĶԪأʹòԱԪصֵͬ + */ + public void removeDuplicateValues() { + for (int i = 0; i < this.size; i++) { + if (i + 1 >= this.size) { + return; + } + if (this.get(i).equals(this.get(i+1))) { + remove(i+1); + i--; + } + } + } + + /** + * ֪еԪֵУԵ洢ṹ дһЧ㷨ɾֵminСmaxԪأдԪأ + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + if (min >= max) { + throw new IllegalArgumentException(); + } + for (int i = 0; i < this.size; i++) { + if ((Integer)this.get(i) > max) { + remove(i, this.size-1); + } + } + } + + /** + * 赱ǰͲlistָԪֵУͬһеԪֵͬ + * ҪCԪΪǰlistԪصĽұCеԪֵ + * TODO + * @param list + */ + public LinkedList intersection(LinkedList list) { + return null; + } + + @Override + public String toString() { + StringBuffer list = new StringBuffer(); + list.append("List:["); + Node node = head.next; + for (int i = 0; i < size; i++) { + list.append(node.data); + node = node.next; + if (i != size -1) { + list.append(", "); + } + } + list.append("]"); + return list.toString(); + } +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/List.java b/group22/627559964/src/com/coding/basic/List.java new file mode 100644 index 0000000000..6f8deaac0a --- /dev/null +++ b/group22/627559964/src/com/coding/basic/List.java @@ -0,0 +1,17 @@ +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(); + + public Iterator iterator(); + +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/Queue.java b/group22/627559964/src/com/coding/basic/Queue.java new file mode 100644 index 0000000000..965894a9ea --- /dev/null +++ b/group22/627559964/src/com/coding/basic/Queue.java @@ -0,0 +1,35 @@ +package com.coding.basic; + +/** + * Զ + * + * @author xiongrui233 + * + */ +public class Queue { + + private LinkedList elements = new LinkedList();; + + private int size = 0; + + public void enQueue(Object o) { + elements.add(o); + size ++; + } + + public Object deQueue() { + size --; + return elements.removeLast(); + } + + public boolean isEmpty() { + if (size == 0) { + return true; + } + return false; + } + + public int size() { + return size; + } +} \ No newline at end of file diff --git a/group22/627559964/src/com/coding/basic/Stack.java b/group22/627559964/src/com/coding/basic/Stack.java new file mode 100644 index 0000000000..84e90bfb75 --- /dev/null +++ b/group22/627559964/src/com/coding/basic/Stack.java @@ -0,0 +1,58 @@ +package com.coding.basic; + +/** + * Զstack + * + * @author xiongrui233 + * + */ +public class Stack { + + //Ԫؼ + private ArrayList elementData = new ArrayList(); + + /** + * ջѹԪ + * @param o + */ + public void push(Object o) { + elementData.add(0,o); + } + + /** + * ջԪ,ƳջԪ + * @return obj + */ + public Object pop() { + Object obj = elementData.get(0); + elementData.remove(0); + return obj; + } + + /** + * ջԪ,ƳջԪ + * @return obj + */ + public Object peek() { + return elementData.get(0); + } + + /** + * жϸջǷΪ + * @return true/false + */ + public boolean isEmpty() { + if (elementData.size() != 0) { + return false; + } + return true; + } + + /** + * ջĴС + * @return size + */ + public int size() { + return elementData.size(); + } +} \ No newline at end of file diff --git a/group22/627559964/src/demo/Demo.java b/group22/627559964/src/demo/Demo.java new file mode 100644 index 0000000000..4fbb5c6b40 --- /dev/null +++ b/group22/627559964/src/demo/Demo.java @@ -0,0 +1,86 @@ +package demo; + +import java.util.Arrays; +import java.util.PriorityQueue; + +import com.coding.basic.ArrayList; +import com.coding.basic.Iterator; +import com.coding.basic.LinkedList; +import com.coding.basic.List; + +public class Demo { + public static void main(String[] args) { + +// List list = new ArrayList(); +// for (int i = 0; i < 12; i++) { +// list.add(new Integer(123)); +// } +// list.add(3, new Integer(233)); +// list.add(3, new Double(233.33)); +// list.remove(6); +// System.out.println("List:" + list); +// Double kk = (Double) list.get(3); +// Iterator it = list.iterator(); +// while (it.hasNext()) { +// System.out.println(it.next()); +// } + + LinkedList list = new LinkedList(); + list.add(1); + list.add(2); + list.add(3); + list.add(5); + list.add(0, 0); + list.add(2, 4); + + System.out.println(list); + + System.out.println(list.size()); + + System.out.println(list.get(4)); + + System.out.println(list.remove(4)); + + System.out.println(list); + + System.out.println(list.reverse()); + + Iterator it = list.iterator(); + while (it.hasNext()) { + System.out.print(it.next() + " "); + } + System.out.println(); + + list.removeFirstHalf(); + System.out.println(list); + + list.remove(0, 1); + System.out.println(list); + + LinkedList ls = new LinkedList(); + list.add(6); + list.add(7); + list.add(8); + ls.add(1); + ls.add(2); + System.out.println(list); + System.out.println(ls); + System.out.println(Arrays.toString(list.getElements(ls))); + + ls.add(6); + list.subtract(ls); + System.out.println(list); + + list.add(1, 6); +// list.add(1, 6); + System.out.println(list); +// list.removeDuplicateValues(); +// System.out.println(list); + + System.out.println("End"); + + list.removeRange(4, 7); + System.out.println(list); + + } +} diff --git a/group22/627559964/test/com/coderising/array/TestArrayUtil.java b/group22/627559964/test/com/coderising/array/TestArrayUtil.java new file mode 100644 index 0000000000..f597900492 --- /dev/null +++ b/group22/627559964/test/com/coderising/array/TestArrayUtil.java @@ -0,0 +1,69 @@ +package com.coderising.array; + +import static org.junit.Assert.*; + +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Test; + +import com.sun.scenario.effect.Merge; + +public class TestArrayUtil { + + @Test + public void testReverseArray() { + try { + int[] number = {1,2,3}; + Assert.assertEquals("[3, 2, 1]", Arrays.toString(ArrayUtil.reverseArray(number))); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testRemoveZero() { + int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; + Assert.assertEquals("[1, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5]", Arrays.toString(ArrayUtil.removeZero(oldArr))); + } + + @Test + public void testMerge() { + int[] a1 = {3, 5, 7, 8}; + int[] a2 = {4, 5, 6, 7}; + Assert.assertEquals("[3, 4, 5, 5, 6, 7, 7, 8]", Arrays.toString(ArrayUtil.merge(a1, a2))); + } + + @Test + public void testGrow() { + int[] oldArray = {2,3,6}; + int size = 3; + Assert.assertEquals("[2, 3, 6, 0, 0, 0]", Arrays.toString(ArrayUtil.grow(oldArray, size))); + } + + @Test + public void testFibonacci() { + int max = 15; + Assert.assertEquals("[1, 1, 2, 3, 5, 8, 13]", Arrays.toString(ArrayUtil.fibonacci(max))); + } + + @Test + public void testGetPrimes() { + int max = 23; + System.out.println(Arrays.toString(ArrayUtil.getPrimes(max))); + Assert.assertEquals("[2, 3, 5, 7, 11, 13, 17, 19]", Arrays.toString(ArrayUtil.getPrimes(max))); + } + + @Test + public void testGetPerfectNumbers() { + Assert.assertEquals("[6, 28, 496]", Arrays.toString(ArrayUtil.getPerfectNumbers(1000))); + } + + @Test + public void testJoin() { + int[] array= {3,8,9}; + String seperator = "-"; + Assert.assertEquals("3-8-9", ArrayUtil.join(array, seperator)); + } +} diff --git a/group22/627559964/test/com/coding/basic/TestArrayList.java b/group22/627559964/test/com/coding/basic/TestArrayList.java new file mode 100644 index 0000000000..68dabbb042 --- /dev/null +++ b/group22/627559964/test/com/coding/basic/TestArrayList.java @@ -0,0 +1,59 @@ +package com.coding.basic; + +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TestArrayList { + + private List list = null; + + @Before + public void init() { + list = new ArrayList(); + + list.add(0); + list.add(1); + list.add(3); + } + + @Test + public void addTest () { + list.add(2,2); +// System.out.println(list.toString()); + Assert.assertEquals("[0, 1, 2, 3]", list.toString()); + } + + @Test + public void getTest () { + Assert.assertEquals(3, list.get(2)); + } + + @Test + public void removeTest () { + list.remove(0); +// System.out.println(list.toString()); + Assert.assertEquals("[1, 3]", list.toString()); + } + + @Test + public void sizeTest () { + Assert.assertEquals(3, list.size()); + } + + @Test + public void iteratorTest () { + Object[] obj = new Object[list.size()]; + Iterator it = list.iterator(); + int i = 0; + while (it.hasNext()) { + obj[i] = it.next(); + i ++; + } +// System.out.println(Arrays.toString(obj)); + Assert.assertEquals(Arrays.toString(obj), list.toString()); + } + +} diff --git a/group22/735371210/.gitignore b/group22/735371210/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group22/735371210/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/liuxin/src/com/coderising/download/.project b/group22/735371210/.project similarity index 93% rename from liuxin/src/com/coderising/download/.project rename to group22/735371210/.project index 9360f320db..1e6bc81917 100644 --- a/liuxin/src/com/coderising/download/.project +++ b/group22/735371210/.project @@ -1,6 +1,6 @@ - download + task1 diff --git a/group22/735371210/src/task1/basic/Iterator.java b/group22/735371210/src/task1/basic/Iterator.java new file mode 100644 index 0000000000..ceed20b8ae --- /dev/null +++ b/group22/735371210/src/task1/basic/Iterator.java @@ -0,0 +1,8 @@ +package task1.basic; + +public interface Iterator { + + public boolean hasNext(); + public Object next(); + +} diff --git a/group22/735371210/src/task1/basic/LinkedList.java b/group22/735371210/src/task1/basic/LinkedList.java new file mode 100644 index 0000000000..02177df4ea --- /dev/null +++ b/group22/735371210/src/task1/basic/LinkedList.java @@ -0,0 +1,140 @@ +package task1.basic; + +public class LinkedList implements List{ + + private Node head = new Node(); + private int size; + + private static class Node{ + Object data; + Node next; + } + + + public void add(Object o){ + addLast(o); + + } + public void add(int index ,Object o){ + if(index<0 || index>size -1){ + throw new ArrayIndexOutOfBoundsException(); + } + + Node node=head; + + Node newNode=new Node(); + + for(int i =0;ielementData.length){ + grow(minLength); + + } + } + + public void grow(int minLength){ + + int oldLength = elementData.length; + int newLength = oldLength + oldLength>>1; + + if(newLength < minLength){ + newLength=minLength; + } + + elementData= Arrays.copyOf(elementData, newLength); + + + + } + public void add(int index ,Object o){ + checkLength(size+1); + System.arraycopy(elementData, index, elementData, index+1, size-index); + elementData[index]=o; + size++; + + } + public Object get(int index){ + + return elementData[index]; + + + } + public Object remove(int index){ + + Object element=elementData[index]; + + System.arraycopy(elementData, index+1, elementData, index, size-index-1); + + elementData[size-1]=null; + + size--; + + return element; + } + + public int size(){ + + return size; + } + + public Iterator iterator(){ + return new ArrayListIterator(); + } + + class ArrayListIterator implements Iterator{ + + int pos=0; + + public boolean hasNext(){ + + if(elementData[pos]!=null){ + return true; + } + + return false; + + } + + public Object next(){ + + return elementData[pos++]; + } + + } + public static void main(String[] args){ + MyArrayList my=new MyArrayList(); + my.add(0); + my.add(1); + my.add(2,10); + my.add(1,11); + my.add(3,32); + + Object ele=my.remove(2); + + System.out.println(ele); + System.out.println(my.get(1)); + System.out.println(my.size()); + + System.out.println("---------"); + + Iterator it=my.iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + + + + } + +} diff --git a/group22/735371210/src/task1/basic/Queue.java b/group22/735371210/src/task1/basic/Queue.java new file mode 100644 index 0000000000..7ade2226c4 --- /dev/null +++ b/group22/735371210/src/task1/basic/Queue.java @@ -0,0 +1,45 @@ +package task1.basic; + +import java.util.LinkedList; + +public class Queue { + + private LinkedList q=new LinkedList(); + + public void enQueue(Object o){ + + q.addLast(o); + } + + public Object deQueue(){ + return q.removeFirst(); + + } + + public int size(){ + + return q.size(); + } + + public static void main(String[] args){ + Queue testQ= new Queue(); + + testQ.enQueue(11); + testQ.enQueue(12); + + testQ.enQueue(13); + + System.out.println(testQ.size()); + + Object s1=testQ.deQueue(); + System.out.println(s1); + + Object s2=testQ.deQueue(); + System.out.println(s2); + + + + + } + +} diff --git a/group22/735371210/src/task1/basic/Stack.java b/group22/735371210/src/task1/basic/Stack.java new file mode 100644 index 0000000000..8aa7d2c5c1 --- /dev/null +++ b/group22/735371210/src/task1/basic/Stack.java @@ -0,0 +1,40 @@ +package task1.basic; + +import java.util.ArrayList; +public class Stack { + + private ArrayList elementData =new ArrayList(); + + public void push(Object o){ + + elementData.add(o); + } + + public Object pop(){ + + return elementData.remove(size()-1); + + } + + public boolean isEmpty(){ + return elementData.isEmpty(); + + } + + public Object peek(){ + + return elementData.get(size()-1); + + + } + + public int size(){ + return elementData.size(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/group22/735371210/src/task2/week2/array/ArrayUtil.java b/group22/735371210/src/task2/week2/array/ArrayUtil.java new file mode 100644 index 0000000000..22492679fa --- /dev/null +++ b/group22/735371210/src/task2/week2/array/ArrayUtil.java @@ -0,0 +1,252 @@ +package task2.week2.array; + +public class ArrayUtil { + + public static void main(String[] args){ + ArrayUtil t=new ArrayUtil(); + int[] intArray={1,3,4}; + int[] array1={1,4,5,8}; + int[] array2={3,5,9}; + + String str=t.join(intArray,"-"); + + for(int i:t.merge(array1,array2)){ + + System.out.println(i); + } + + + } + /** + * 给定一个整形数组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=0; + for(int i=0;i2){ + array[0]=1; + array[1]=1; + int i=2; + + while(array[i-1]=max){ + array[i-1]=0; + } + } + + + return array; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + + int[] newArray = new int[max]; + if (max > 2) { + + int size = 0, j = 0; + + for (int i = 2; i < max; i++) { + for (j = 2; j < i / 2 + 1; j++) { + + if (i % j == 0) { + + break; + + } + + } + + if (j == i / 2 + 1) { + newArray[size++] = i; + } + + } + + } + + return newArray; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + int[] prefectArray=new int[max]; + int k=0; + + for(int i=1;i parameters) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, 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字段中。 + + */ + String jsp=""; + + Map viewParams=new HashMap(); + + Element ele=getNode(actionName); + + String className=ele.attributeValue("class"); + + Class actionClass=Class.forName(className); + + Object action=actionClass.newInstance(); + + for(Map.Entry entry :parameters.entrySet()){ + + + Method m=actionClass.getMethod("set"+entry.getKey().substring(0,1).toUpperCase()+entry.getKey().substring(1), String.class); + + m.invoke(action, entry.getValue()); + + + } + + Method execute =actionClass.getMethod("execute"); + String result=(String)execute.invoke(action); + + System.out.println(result); + + Method[] methods=actionClass.getDeclaredMethods(); + + for(Method m : methods){ + if(m.getName().startsWith("get")){ + String value =(String) m.invoke(action); + + String key=m.getName().substring(3); + key=key.substring(0,1).toLowerCase()+key.substring(1); + + viewParams.put(key,value); + + + } + } + + for(Element e:(List) ele.elements("result")){ + + if(e.attributeValue("name").equals(result)){ + + jsp=e.getText(); + } + + } + + View view=new View(); + view.setJsp(jsp); + + view.setParameters(viewParams); + + + return view; + } + + + public static Element getNode(String actionName){ + Element ele=null; + + SAXReader reader =new SAXReader(); + + InputStream in =Struts.class.getResourceAsStream("struts.xml"); + + try { + Document doc =reader.read(in); + Element root =doc.getRootElement(); + + List childNode= root.elements(); + + + for(Element e:childNode){ + + if(e.attributeValue("name").equals(actionName)){ + ele=e; + break; + } + + } + + + } catch (DocumentException ex) { + + ex.printStackTrace(); + } + + return ele; + + + + } + + + +} + diff --git a/group22/735371210/src/task2/week2/struts/StrutsTest.java b/group22/735371210/src/task2/week2/struts/StrutsTest.java new file mode 100644 index 0000000000..4c9ad36231 --- /dev/null +++ b/group22/735371210/src/task2/week2/struts/StrutsTest.java @@ -0,0 +1,44 @@ +package task2.week2.struts; + +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 ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { + + 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 ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { + 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/group22/735371210/src/task2/week2/struts/View.java b/group22/735371210/src/task2/week2/struts/View.java new file mode 100644 index 0000000000..9f5851bc8f --- /dev/null +++ b/group22/735371210/src/task2/week2/struts/View.java @@ -0,0 +1,23 @@ +package task2.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/group22/735371210/src/task2/week2/struts/struts.out.xml b/group22/735371210/src/task2/week2/struts/struts.out.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/group22/735371210/src/task2/week2/struts/struts.xml b/group22/735371210/src/task2/week2/struts/struts.xml new file mode 100644 index 0000000000..b47a193398 --- /dev/null +++ b/group22/735371210/src/task2/week2/struts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group22/77253242/coding2017/src/ArrayList.java b/group22/77253242/coding2017/src/ArrayList.java new file mode 100644 index 0000000000..c911129893 --- /dev/null +++ b/group22/77253242/coding2017/src/ArrayList.java @@ -0,0 +1,74 @@ +import javax.swing.plaf.basic.BasicTreeUI; +import java.security.SignatureException; +import java.util.Arrays; + +/** + * Created by fantasy on 2017-03-13. + */ + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[10]; + + public void add(Object o) { + if(size >= elementData.length) + { + elementData= Arrays.copyOf(elementData, size+10); + } + elementData [++size] = o; + } + + public void add(int index, Object o) { + if(size >= elementData.length) + { + elementData = new Object[size + 10]; + } + if(size > index) + { + elementData[++size] = o; + } + else + { + for(int i = size;i>index;i--) + { + elementData [i + 1] = elementData [i]; + } + } + elementData [index] = o; + size++; + } + + public Object get(int index) { + if(index < 0 || index > size) + { + throw new IndexOutOfBoundsException("size:" + size + ",index:"+index); + } + return elementData[size]; + } + + public Object remove(int index) { + if(size > index) + { + Object OldValue = elementData[index]; + for(int i = index;i<= size;) + { + elementData[i] = elementData[++i]; + } + return OldValue; + } + throw new IndexOutOfBoundsException("size:"+ size + ",index:" + index); + } + + + public int size() { + return size; + } + + public Iterator iterator() { + return null; + } + + +} \ No newline at end of file diff --git a/group22/77253242/coding2017/src/BinaryTreeNode.java b/group22/77253242/coding2017/src/BinaryTreeNode.java new file mode 100644 index 0000000000..20b7dd99fb --- /dev/null +++ b/group22/77253242/coding2017/src/BinaryTreeNode.java @@ -0,0 +1,33 @@ +/** + * Created by fantasy on 2017-03-13. + */ +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/group22/77253242/coding2017/src/Iterator.java b/group22/77253242/coding2017/src/Iterator.java new file mode 100644 index 0000000000..5d970abec8 --- /dev/null +++ b/group22/77253242/coding2017/src/Iterator.java @@ -0,0 +1,9 @@ +/** + * Created by fantasy on 2017-03-13. + */ + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group22/77253242/coding2017/src/LinkedList.java b/group22/77253242/coding2017/src/LinkedList.java new file mode 100644 index 0000000000..e9fd8547d7 --- /dev/null +++ b/group22/77253242/coding2017/src/LinkedList.java @@ -0,0 +1,238 @@ +import java.net.IDN; + +public class LinkedList implements List { + + private Node head; + + private Node firstNode; + private Node lastNode; + private int size = 0; + + + public void add(Object o){ + linkLast(o); + + } + public void add(int index , Object o){ + if(index > size()) + { + throw new IndexOutOfBoundsException("index:"+ index + ",size:"+ size()); + } + if(size == 0) + { + linkLast(o); + } + else + { + Node node = node(index); + Node newNode = new Node(o,node.prev,node); + node.setPrev(newNode); + } + ++size; + } + public Object get(int index){ + return node(index).getData(); + } + public Object remove(int index){ + if(index >size()) + { + throw new IndexOutOfBoundsException("index:"+ index + ",size:"+ size()); + } + Node node = node(index); + node.prev.next = node.next; + node.next.prev = node.prev; + --size; + return node; + } + + public int size(){ + return size; + } + + public void addFirst(Object o){ + linkLast(o); + } + public void addLast(Object o){ + if(lastNode == null) + { + lastNode = new Node(o,firstNode,null); + } + else + { + Node node = lastNode; + node.next = new Node(o,node,null); + lastNode = node.next; + } + ++size; + } + public Object removeFirst(){ + if(size > 0 ) + { + Node node = firstNode; + firstNode = node.next; + --size; + return node.getData(); + } + return null; + } + public Object removeLast(){ + if(size > 0 ) + { + Node node = lastNode; + lastNode = node.prev; + --size; + return node.getData(); + } + return null; + } + public Iterator iterator(){ + return null; + } + + LinkedList.Node node(int index) + { + if(index < size()) + { + Node node = firstNode; + for(int i=0;i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + for(int i=0;i5->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/group22/77253242/coding2017/src/List.java b/group22/77253242/coding2017/src/List.java new file mode 100644 index 0000000000..c4e9df138a --- /dev/null +++ b/group22/77253242/coding2017/src/List.java @@ -0,0 +1,10 @@ +/** + * Created by fantasy on 2017-03-13. + */ +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/group22/77253242/coding2017/src/Main.java b/group22/77253242/coding2017/src/Main.java new file mode 100644 index 0000000000..1f5e6bdd9c --- /dev/null +++ b/group22/77253242/coding2017/src/Main.java @@ -0,0 +1,9 @@ +import java.util.*; +import java.util.LinkedList; + +public class Main { + + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/group22/77253242/coding2017/src/Queue.java b/group22/77253242/coding2017/src/Queue.java new file mode 100644 index 0000000000..4e0fe62925 --- /dev/null +++ b/group22/77253242/coding2017/src/Queue.java @@ -0,0 +1,25 @@ +import java.awt.image.AreaAveragingScaleFilter; + +/** + * Created by fantasy on 2017-03-13. + */ +public class Queue { + ArrayList arrayList = new ArrayList(); + + + public void enQueue(Object o){ + arrayList.add(o); + } + + public Object deQueue(){ + return arrayList.remove(0); + } + + public boolean isEmpty(){ + return !(arrayList.size() >0); + } + + public int size(){ + return arrayList.size(); + } +} \ No newline at end of file diff --git a/group22/77253242/coding2017/src/Stack.java b/group22/77253242/coding2017/src/Stack.java new file mode 100644 index 0000000000..d203b6ba29 --- /dev/null +++ b/group22/77253242/coding2017/src/Stack.java @@ -0,0 +1,34 @@ +import java.util.EmptyStackException; + +/** + * Created by fantasy on 2017-03-13. + */ +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + if(elementData.size() == 0) + { + return elementData.remove(elementData.size() - 1 ); + } + return null; + } + + public Object peek(){ + if(elementData.size() == 0 ) + { + return elementData.get(elementData.size() - 1); + } + throw new EmptyStackException(); + } + public boolean isEmpty(){ + return !(elementData.size()>0); + } + public int size(){ + return elementData.size(); + } +} diff --git "a/group22/910725683/CPU\357\274\214\345\206\205\345\255\230\357\274\214\347\241\254\347\233\230\357\274\214\346\214\207\344\273\244\344\273\245\345\217\212\345\256\203\344\273\254\344\271\213\351\227\264\347\232\204\345\205\263\347\263\273.md" "b/group22/910725683/CPU\357\274\214\345\206\205\345\255\230\357\274\214\347\241\254\347\233\230\357\274\214\346\214\207\344\273\244\344\273\245\345\217\212\345\256\203\344\273\254\344\271\213\351\227\264\347\232\204\345\205\263\347\263\273.md" new file mode 100644 index 0000000000..04e93eb38e --- /dev/null +++ "b/group22/910725683/CPU\357\274\214\345\206\205\345\255\230\357\274\214\347\241\254\347\233\230\357\274\214\346\214\207\344\273\244\344\273\245\345\217\212\345\256\203\344\273\254\344\271\213\351\227\264\347\232\204\345\205\263\347\263\273.md" @@ -0,0 +1,27 @@ +##CPU,内存,硬盘,指令以及它们之间的关系(2017.03.12) + +>对这块也说不太深,大体写点吧 + +### CPU + +CPU,就是中央处理器(Central Processing Unit),就是一大块集成电路 :) + +这里面呢,有这么几个重要的东西:ALU、寄存器、时钟。 + +ALU:就是算数逻辑单元,我的理解,功能上就是把几个基本的逻辑计算、数学计算以电路形式实现出来。比如加法啊、与或非门啊、位移啊什么的。 + +寄存器:听名字,就是存储用的,保存要干的任务、给ALU提供输入、保存ALU的输出。 + +时钟:这个。。。,就是一个计时器。为啥需要这个计时器呢(按照上面讲的,运算已经都够完成了)?可以理解为乐队的指挥、龙舟上的鼓手,作用就是产生一个频率信号,用来指挥上面那俩按照一个节奏有序的工作。为了快速的完成任务,这个频率需要非常快,有多快呢?目前3.5GHz已经很常见了,也就是说1s运算350,000,000次。 + +### 内存 + +内存呢,也是用来存储数据的。前面说了,CPU里面已经有了寄存器这么个用来存储的东西,为啥还要个内存呢?主要原因就是寄存器又小又贵,小到不能存储所有的内容(基本上存不了什么),贵到不好任性的扩容(要满足CPU那么快的速度还是有难度的)。有人就想出了另一种方案,把不那么常用的数据呢,放在不那么快,但是更大的存储原件里面,也就是内存。平常存储点堆栈啊、缓冲什么的。这样,寄存器只要保存数据在内存中的位置,用的时候去内存取出来就好了。内存还可以分为RAM与ROM,不再细说。 + +### 硬盘 + +要硬盘,是因为内存也不够用了。。。当然,硬盘比内存还要慢,一般也会比内存大。用的时候,先从硬盘读出来放到内存就好了。 + +### 指令 + +指令,就是给CPU用的Java(当然写起来远没有Java方便),用来告诉CPU要干什么。 \ No newline at end of file diff --git a/group22/910725683/RemoteSystemsTempFiles/.project b/group22/910725683/RemoteSystemsTempFiles/.project new file mode 100644 index 0000000000..5447a64fa9 --- /dev/null +++ b/group22/910725683/RemoteSystemsTempFiles/.project @@ -0,0 +1,12 @@ + + + RemoteSystemsTempFiles + + + + + + + org.eclipse.rse.ui.remoteSystemsTempNature + + diff --git a/group22/910725683/week01/.classpath b/group22/910725683/week01/.classpath new file mode 100644 index 0000000000..1b83178c00 --- /dev/null +++ b/group22/910725683/week01/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/group22/910725683/week01/.gitignore b/group22/910725683/week01/.gitignore new file mode 100644 index 0000000000..6a59c3a991 --- /dev/null +++ b/group22/910725683/week01/.gitignore @@ -0,0 +1,4 @@ +/bin/ +/.settings/ +.classpatch +.prject \ No newline at end of file diff --git a/group22/910725683/week01/.project b/group22/910725683/week01/.project new file mode 100644 index 0000000000..3b3c4fa7ee --- /dev/null +++ b/group22/910725683/week01/.project @@ -0,0 +1,17 @@ + + + week01 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group22/910725683/week01/src/com/coding/basic/ArrayList.java b/group22/910725683/week01/src/com/coding/basic/ArrayList.java new file mode 100644 index 0000000000..acc0e9f8f4 --- /dev/null +++ b/group22/910725683/week01/src/com/coding/basic/ArrayList.java @@ -0,0 +1,98 @@ +package com.coding.basic; +import java.util.Arrays; + +public class ArrayList implements List { + + //ʼ// + private final int DEFAULT_CAPICITY=7; + + //Ԫظ// + private int size = 0; + + private Object[] elementData = new Object[DEFAULT_CAPICITY]; + + public void add(Object o){ + ensureCapcity(size+1); + elementData[size++]=o; + } + public void add(int index, Object o){ + //indexҪ// + checkIndex(index); + ensureCapcity(size+1); + /* indexԪһλ,indexʼƶעindex0ʼ + * Ҫ+1򳤶Ϊsize-((index)+1)+1 + */ + System.arraycopy(elementData, index, elementData, index+1, size-index); + elementData[index]=o; + size++; + } + + public Object get(int index){ + checkIndex(index); + return elementData[index]; + } + + public Object remove(int index){ + checkIndex(index); + Object temp=elementData[index]; + /* indexԪһλ,index+1ʼƶעindex0ʼ + * Ҫ+1򳤶Ϊsize-((index+1)+1)+1 + */ + System.arraycopy(elementData, index+1, elementData, index, size-index-1); + size--; + return temp; + } + + public int size(){ + return size; + } + + public Iterator iterator(){ + return new Iterator(); + } + + private class Iterator{ + private int index=0; + public boolean hasNext(){ + return index=size){ + throw new IndexOutOfBoundsException("get " + index+" in "+size); + } + } + + //жǷҪݲ// + private void ensureCapcity(int size){ + int oldLength=elementData.length; + if (size>=oldLength){ + //util.ArrayListеĹʽԴʹõ12// + int newLength=oldLength/2+oldLength; + if (newLength7->10 , úΪ 10->7->3 + */ + public void reverse(){ + /*ָ룬ʼʱָͷͷһ(ǰָ롢ָ) + *ѭÿƶ1ָƵβsize-1ڵҪƶ(size-1)-1 + *ȱǰֵָtempǰͷȻƶǰָ + *ƶ󣬽ǰָĽڵӵͷʼһƶ + *ѭע⵽ʵֻоĵڶڵ㵽ڸڵ㣬Ҫͷβڵ + *βڵҪӵͷͷڵָÿգȻ1<->2 + *άͷβ + */ + Node current=head; + Node currentAfter=current.next; + Node temp; + for (int i=0;i5->7->8 , ɾԺֵΪ 7->8 + * list = 2->5->7->8->10 ,ɾԺֵΪ7,8,10 + */ + public void removeFirstHalf(){ + //intضϣС// + int removeLength = size / 2; + for (int i=1;i<=removeLength;i++){ + removeFirst(); + } + } + + /** + * ӵiԪؿʼ ɾlength Ԫ עi0ʼ + * @param i + * @param length + */ + public void remove(int i, int length){ + checkIndex(i); + length=length+i-1; + if (i+length-1>size){ + length=size-i; + } + //ӺǰɾֹԽ// + for (int k=length;k>=i;k--){ + remove(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 indexLength=list.size(); + int[] result=new int[indexLength]; + for (int i=0;isize){ + result[i]=0; + }else{ + result[i]=(int)list.get(index); + } + } + return result; + } + + /** + * ֪еԪֵУԵ洢ṹ + * ӵǰɾlistгֵԪ + * @param list + */ + //ע⵽ѭlistʱ򣬱ڲѭıȽĽڵ±겢// + public void subtract(LinkedList list){ + int startIndex=0; + Iterator iter=list.iterator(); + while(iter.hasNext()){ + int src =(int) iter.next(); + while(startIndexmax){ + if (isHeadNoed){ + current=current.next; + removeFirst(); + }else{ + temp.next=current.next; + current=current.next; + size--; + } + }else{ + temp=current; + current=current.next; + isHeadNoed=false; + } + + } + } + + /** + * 赱ǰͲlistָԪֵУͬһеԪֵͬ + * ҪCԪΪǰlistԪصĽұCеԪֵ + * @param list + */ + //ע⵽ѭ±λõ// + public LinkedList intersection( LinkedList list){ + LinkedList result = new LinkedList(); + int startIndex = 0; + for (Iterator iter = list.iterator();iter.hasNext();){ + int src = (int) iter.next(); + while (startIndex=size){ + throw new IndexOutOfBoundsException("get " + index+" in "+size); + } + } + + public String toString(){ + StringBuilder sb = new StringBuilder(); + Node current = head; + for (int i=0;i"); + } + current=current.next; + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/group22/910725683/week01/src/com/coding/basic/List.java b/group22/910725683/week01/src/com/coding/basic/List.java new file mode 100644 index 0000000000..29caa79f69 --- /dev/null +++ b/group22/910725683/week01/src/com/coding/basic/List.java @@ -0,0 +1,10 @@ +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(); +} \ No newline at end of file diff --git a/group22/910725683/week01/src/com/coding/basic/Queue.java b/group22/910725683/week01/src/com/coding/basic/Queue.java new file mode 100644 index 0000000000..6e1b288ebc --- /dev/null +++ b/group22/910725683/week01/src/com/coding/basic/Queue.java @@ -0,0 +1,26 @@ +package com.coding.basic; + +public class Queue { + + private LinkedList queue = new LinkedList(); + + public void enQueue(Object o){ + queue.add(o); + } + + public Object deQueue(){ + return queue.removeFirst(); + } + + public boolean isEmpty(){ + return queue.size()==0; + } + + public int size(){ + return queue.size(); + } + + public String toString() { + return queue.toString(); + } +} \ No newline at end of file diff --git a/group22/910725683/week01/src/com/coding/basic/Stack.java b/group22/910725683/week01/src/com/coding/basic/Stack.java new file mode 100644 index 0000000000..a8d071b707 --- /dev/null +++ b/group22/910725683/week01/src/com/coding/basic/Stack.java @@ -0,0 +1,27 @@ +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(){ + return (elementData.size())==0; + } + public int size(){ + return elementData.size(); + } + public String toString() { + return elementData.toString(); + } +} \ No newline at end of file diff --git a/group22/910725683/week01/test/com/coding/basic/ArrayListTest.java b/group22/910725683/week01/test/com/coding/basic/ArrayListTest.java new file mode 100644 index 0000000000..e0940e8acb --- /dev/null +++ b/group22/910725683/week01/test/com/coding/basic/ArrayListTest.java @@ -0,0 +1,53 @@ +package com.coding.basic; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ArrayListTest { + + ArrayList al = new ArrayList(); + + @Test + public void testAddObject() { + for (int i=1;i<=5;i++){ + al.add(i); + } + } + + @Test + public void testAddIntObject() { + testAddObject(); + al.add(3, 12); + System.out.println("inser index 3 value 12 : "+al.toString()); + } + + @Test + public void testGet() { + testAddObject(); + System.out.println("get index 4 : "+al.get(4)); + } + + @Test + public void testRemove() { + testAddObject(); + System.out.println("remove index 3 : "+al.remove(3)); + } + + @Test + public void testSize() { + testAddObject(); + System.out.println("get size : "+al.size()); + } + + @Test + public void testIterator() { + fail("Not yet implemented"); + } + + @Test + public void testToString() { + fail("Not yet implemented"); + } + +} diff --git a/group22/910725683/week01/test/com/coding/basic/BinaryTreeNodeTest.java b/group22/910725683/week01/test/com/coding/basic/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..b32b779091 --- /dev/null +++ b/group22/910725683/week01/test/com/coding/basic/BinaryTreeNodeTest.java @@ -0,0 +1,47 @@ +package com.coding.basic; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.coding.basic.BinaryTreeNode; + +public class BinaryTreeNodeTest { + + BinaryTreeNode btn = new BinaryTreeNode(); + + @Test + public void testPreOrder() { + testInsert(); + System.out.print("preOrde : "); + btn.preOrder(btn); + System.out.println(""); + } + + @Test + public void testInOrder() { + testInsert(); + System.out.print("inOrder : "); + btn.inOrder(btn); + System.out.println(""); + } + + @Test + public void testPostOrder() { + testInsert(); + System.out.print("postOrder : "); + btn.postOrder(btn); + System.out.println(""); + } + + @Test + public void testInsert() { + btn.insert(45); + btn.insert(24); + btn.insert(53); + btn.insert(12); + btn.insert(37); + btn.insert(93); + } + +} diff --git a/group22/910725683/week01/test/com/coding/basic/LinkedListTest.java b/group22/910725683/week01/test/com/coding/basic/LinkedListTest.java new file mode 100644 index 0000000000..2d22e2e92d --- /dev/null +++ b/group22/910725683/week01/test/com/coding/basic/LinkedListTest.java @@ -0,0 +1,137 @@ +package com.coding.basic; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.coding.basic.LinkedList; + +public class LinkedListTest { + LinkedList ll =new LinkedList(); + @Test + public void testAddObject() { + for (int i=0;i<9;i++){ + ll.add(i); + } + } + + @Test + public void testAddIntObject() { + testAddObject(); + ll.add(4, 22); + ll.add(0, 23); + System.out.println("add int : " + ll.toString()); + } + + @Test + public void testGet() { + testAddObject(); + System.out.println("get index 3 : "+ll.get(3)); + } + + @Test + public void testRemoveInt() { + testAddObject(); + System.out.println("remove index 5 : "+ll.get(5)); + } + + @Test + public void testSize() { + testAddObject(); + System.out.println("get size : "+ll.size()); + } + + @Test + public void testAddFirst() { + testAddObject(); + ll.addFirst(12); + System.out.println("add first : "+ll.toString()); + } + + @Test + public void testAddLast() { + testAddObject(); + ll.addLast(23); + System.out.println("add first : "+ll.toString()); + } + + @Test + public void testRemoveFirst() { + testAddObject(); + ll.removeFirst(); + System.out.println("remove first : "+ll.toString()); + } + + @Test + public void testRemoveLast() { + testAddObject(); + ll.removeLast(); + System.out.println("remove last : "+ll.toString()); + } + + @Test + public void testReverse() { + testAddObject(); + ll.reverse(); + System.out.println("reverse : "+ll.toString()); + } + + @Test + public void testRemoveFirstHalf() { + testAddObject(); + ll.removeFirstHalf(); + System.out.println("remove first half : "+ll.toString()); + } + + @Test + public void testRemoveIntInt() { + testAddObject(); + ll.remove(2, 4); + System.out.println("remove index 2 length 4 : "+ll.toString()); + } + + @Test + public void testGetElements() { + testAddObject(); + System.out.println("get index 2 : "+ll.get(2)); + } + + @Test + public void testSubtract() { + testAddObject(); + LinkedList test1 =new LinkedList(); + for (int i=2;i<5;i++){ + test1.add(i); + } + ll.subtract(test1); + System.out.println("subtract "+test1.toString()+" : "+ll.toString()); + } + + @Test + public void testRemoveDuplicateValues() { + testAddObject(); + for (int i=6;i>2;i--){ + ll.add(i,i); + } + ll.removeDuplicateValues(); + System.out.println("remove dupl : "+ll.toString()); + } + + @Test + public void testRemoveRange() { + testAddObject(); + ll.removeRange(3, 6); + System.out.println("remove range[3,6] : "+ll.toString()); + } + + @Test + public void testIntersection() { + testAddObject(); + LinkedList test2 =new LinkedList(); + for (int i=4;i<14;i=i+2){ + test2.add(i); + } + System.out.println("intersection "+test2.toString()+" : "+ll.intersection(test2)); + } + +} diff --git a/group22/910725683/week01/test/com/coding/basic/QueueTest.java b/group22/910725683/week01/test/com/coding/basic/QueueTest.java new file mode 100644 index 0000000000..18cba75d07 --- /dev/null +++ b/group22/910725683/week01/test/com/coding/basic/QueueTest.java @@ -0,0 +1,40 @@ +package com.coding.basic; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.coding.basic.Queue; + +public class QueueTest { + Queue queue = new Queue(); + + @Test + public void testEnQueue() { + for (int i=0;i<10;i++){ + queue.enQueue(i); + } + } + + @Test + public void testDeQueue() { + testEnQueue(); + for (int i=0;i<3;i++){ + System.out.println("deQueue : " + queue.deQueue()); + } + } + + @Test + public void testIsEmpty() { + System.out.println("is empty(true) : "+queue.isEmpty()); + testEnQueue(); + System.out.println("is empty(false) : "+queue.isEmpty()); + } + + @Test + public void testSize() { + testEnQueue(); + System.out.println("size : "+queue.size()); + } + +} diff --git a/group22/910725683/week01/test/com/coding/basic/StackTest.java b/group22/910725683/week01/test/com/coding/basic/StackTest.java new file mode 100644 index 0000000000..0c8095d79c --- /dev/null +++ b/group22/910725683/week01/test/com/coding/basic/StackTest.java @@ -0,0 +1,48 @@ +package com.coding.basic; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.coding.basic.Stack; + +public class StackTest { + Stack stack = new Stack(); + + @Test + public void testPush() { + for (int i = 0; i < 10; i++) { + stack.push(i); + } + } + + @Test + public void testPop() { + testPush(); + for (int i = 0; i < 3; i++) { + System.out.println("pop : "+stack.pop()); + } + } + + @Test + public void testPeek() { + testPush(); + for (int i = 0; i < 3; i++) { + System.out.println("peek : "+stack.peek()); + } + } + + @Test + public void testIsEmpty() { + System.out.println("is empty(true) : "+stack.isEmpty()); + testPush(); + System.out.println("is empty(false) : "+stack.isEmpty()); + } + + @Test + public void testSize() { + testPush(); + System.out.println("size : "+stack.size()); + } + +} diff --git a/group23/.DS_Store b/group23/.DS_Store new file mode 100644 index 0000000000..7e3e6cfac4 Binary files /dev/null and b/group23/.DS_Store differ diff --git a/group23/1028361767/1028361767.md b/group23/1028361767/1028361767.md new file mode 100644 index 0000000000..741976ad6e --- /dev/null +++ b/group23/1028361767/1028361767.md @@ -0,0 +1 @@ +This is 1028361767's project. \ No newline at end of file diff --git a/group23/1028361767/Week1DataStructure/bin/com/coderising/litestruts/struts.xml b/group23/1028361767/Week1DataStructure/bin/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/bin/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/group23/1028361767/Week1DataStructure/src/com/coderising/array/ArrayUtil.java b/group23/1028361767/Week1DataStructure/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..e497a8e251 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,210 @@ +package com.coderising.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 int[] reverseArray(int[] origin){ + int len = origin.length; + int[] ret = new int[len]; + for(int i=0;i len1 && i2 > len2){ + break; + }else if(i1 > len1){ + ret[i++] = array2[i2++]; + }else{ + ret[i++] = array1[i1++]; + } + } + + } + if(sameNum > 0){ + ret = Arrays.copyOf(ret, ret.length - sameNum); + } + return ret; + } + + /** + * 把一个已经存满数据的数组 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[0]; + }else{ + int[] tmp = new int[max + 1]; + int x1 = 1, x2 = 1; + int i = 1, j = 0; + tmp[j++] = x1; + tmp[j++] = x2; + while(true){ + i = x1 + x2; + if(i > max){ + break; + } + x1 = x2; + x2 = i; + tmp[j++] = i; + } + return Arrays.copyOf(tmp, j); + } + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + int[] tmp = new int[max/2 + 1]; + boolean isPrime; + int k = 0; + for(int i=2;i actions = new HashMap(); + + @SuppressWarnings("rawtypes") + public static View runAction(String actionName, Map parameters) throws Exception { + + /* + + 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字段中。 + + */ + //读取xml,把xml信息放到actions + readStrutsXML(); + + Action action = actions.get(actionName); + View view = new View(); + if(action != null){ + Class clazz = Class.forName(action.getClassName()); + Object obj = clazz.newInstance(); + + //根据parameters调用set方法 + initClass(clazz, obj, action, parameters); + + //调用execute方法 + String result = execute(clazz, obj); + //调用所有get方法 + Map resultParameters = getResultParameters(clazz, obj); + + view.setJsp(action.getResults().get(result)); + view.setParameters(resultParameters); + } + + return view; + } + + @SuppressWarnings("rawtypes") + private static Map getResultParameters(Class clazz, Object obj) throws Exception { + Map resultParameters = new HashMap(); + Method[] methods = clazz.getMethods(); + String methodName; + String propName; + String propValue; + for(Method method : methods){ + methodName = method.getName(); + if(methodName.startsWith("get") && !"getClass".equals(methodName)){ + propName = firstLetterLowerCase(methodName.substring(3, methodName.length())); + propValue = (String) method.invoke(obj); + resultParameters.put(propName, propValue); + } + } + return resultParameters; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static String execute(Class clazz, Object obj) throws Exception{ + Method method = clazz.getMethod("execute"); + return (String)method.invoke(obj); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void initClass(Class clazz, Object obj, Action action, Map parameters) throws Exception { + String setMethodName; + Method method = null; + for (String parameter : parameters.keySet()) { + setMethodName = "set" + firstLetterUpperCase(parameter); + method = clazz.getMethod(setMethodName, String.class); + method.invoke(obj, parameters.get(parameter)); + } + } + + private static String firstLetterLowerCase(String string){ + char[] cs = string.toCharArray(); + cs[0] += 32; + return String.valueOf(cs); + } + + private static String firstLetterUpperCase(String string){ + char[] cs = string.toCharArray(); + cs[0] -= 32; + return String.valueOf(cs); + } + + @SuppressWarnings("unchecked") + private static void readStrutsXML() { + SAXReader saxReader = new SAXReader(); + Document document; + try { + document = saxReader.read(new File("src/com/coderising/litestruts/struts.xml")); + } catch (DocumentException e) { + System.out.println("error:file not found"); + return ; + } + Element root = document.getRootElement(); + Iterator actionItr = root.elementIterator(); + Element action; + Action act; + Iterator resultItr; + Element result; + Map results; + while(actionItr.hasNext()){ + action = actionItr.next(); + + resultItr = action.elementIterator(); + results = new HashMap(); + while(resultItr.hasNext()){ + result = resultItr.next(); + results.put(result.attributeValue("name"), result.getStringValue()); + } + + act = new Action(); + act.setName(action.attributeValue("name")); + act.setClassName(action.attributeValue("class")); + act.setResults(results); + + actions.put(act.getName(), act); + } + } + + static class Action { + + private String name; + + private String className; + + private Map results = new HashMap<>(); + + public Map getResults() { + return results; + } + + public void setResults(Map results) { + this.results = results; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + } + +} diff --git a/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/StrutsTest.java b/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..92a6758a69 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/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() 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/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/View.java b/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group23/1028361767/Week1DataStructure/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/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/struts.xml b/group23/1028361767/Week1DataStructure/src/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/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/group23/1028361767/Week1DataStructure/src/com/coding/basic/ArrayList.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/ArrayList.java new file mode 100644 index 0000000000..da0237bdf7 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/ArrayList.java @@ -0,0 +1,80 @@ +package com.coding.basic; + +import java.util.Arrays; + +public class ArrayList implements List { + + private int size = 0; + + private int HALF_MAX_VALUE = Integer.MAX_VALUE; + + private Object[] elementData = new Object[100]; + + public void add(Object o) { + if (noSpace()) { + elementData = grow(); + } + elementData[size++] = o; + } + + public void add(int index, Object o) { + if (index < 0) { + throw new IllegalArgumentException("index must be positive integer"); + } + if (index > size) { + throw new IndexOutOfBoundsException("size is" + size); + } + if (noSpace()) { + elementData = grow(); + } + System.arraycopy(elementData, index, elementData, index + 1, size - index); + elementData[size++] = o; + } + + public Object get(int index) { + if (index < 0) { + throw new IllegalArgumentException("index must be positive integer"); + } + if (index > (size - 1)) { + throw new IndexOutOfBoundsException("size is" + size); + } + return elementData[index]; + } + + public Object remove(int index) { + if (index < 0) { + throw new IllegalArgumentException("index must be positive integer"); + } + if (index > (size - 1)) { + throw new IndexOutOfBoundsException("size is" + size); + } + Object obj = elementData[index]; + System.arraycopy(elementData, index + 1, elementData, index, size - index); + elementData[size-1] = null; + size--; + return obj; + } + + public int size() { + return size; + } + + public Iterator iterator() { + return null; + } + + private boolean noSpace() { + return size == elementData.length; + } + + private Object[] grow() { + int newSize; + if (size < HALF_MAX_VALUE) { + newSize = size * 2; + } else { + newSize = Integer.MAX_VALUE; + } + return Arrays.copyOf(elementData, newSize); + } + +} diff --git a/group23/1028361767/Week1DataStructure/src/com/coding/basic/BinaryTreeNode.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..dced34e873 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/BinaryTreeNode.java @@ -0,0 +1,97 @@ +package com.coding.basic; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private BinaryTreeNode parent; + + public BinaryTreeNode(Object data) { + this.data = data; + } + + 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 void setParent(BinaryTreeNode parent) { + this.parent = parent; + } + + public BinaryTreeNode getParent() { + return parent; + } + + public BinaryTreeNode insert(Object o) { + BinaryTreeNode newNode = new BinaryTreeNode(o); + BinaryTreeNode root = findRoot(this); + if (root.data == null) { + root.data = newNode; + } else { + int newVal = getNodeIntVal(newNode); + insert(root, newNode, newVal); + } + return newNode; + } + + private void insert(BinaryTreeNode node, BinaryTreeNode newNode, int newVal) { + int nodeVal = getNodeIntVal(node); + if (newVal < nodeVal) { + if (node.left == null) { + newNode.parent = node; + node.left = newNode; + } else { + insert(node.left, newNode, newVal); + } + } else { + if (node.right == null) { + newNode.parent = node; + node.right = newNode; + } else { + insert(node.right, newNode, newVal); + } + } + } + + private BinaryTreeNode findRoot(BinaryTreeNode binaryTreeNode) { + while (binaryTreeNode.parent != null) { + binaryTreeNode = binaryTreeNode.parent; + } + return binaryTreeNode; + } + + private int getNodeIntVal(BinaryTreeNode node) { + if (node.data instanceof Integer) { + return ((Integer) node.data).intValue(); + } + return 0; + } + + public int getDataIntVal() { + if (data instanceof Integer) { + return ((Integer) data).intValue(); + } + return 0; + } +} diff --git a/group23/1028361767/Week1DataStructure/src/com/coding/basic/Iterator.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..96adcd6d3a --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Iterator.java @@ -0,0 +1,8 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + + public Object next(); + +} diff --git a/group23/1028361767/Week1DataStructure/src/com/coding/basic/LinkedList.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/LinkedList.java new file mode 100644 index 0000000000..5e241db172 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/LinkedList.java @@ -0,0 +1,244 @@ +package com.coding.basic; + + +import java.util.NoSuchElementException; + +public class LinkedList implements List { + + private Node head; + private int size; + + public void add(Object o) { + Node newNode = new Node(o, null); + if (head == null) { + head = newNode; + } else { + Node tmp = head; + while (tmp.next != null) { + tmp = tmp.next; + } + tmp.next = newNode; + } + size++; + } + + public void add(int index, Object o) { + checkMinBound(index); + checkMaxBound(index, size); + Node newNode = new Node(o, null); + if (index == 0) { + newNode.next = head; + head = newNode; + } else { + int pos = 1; + Node tmp = head; + while (pos != index) { + tmp = tmp.next; + pos++; + } + newNode.next = tmp.next; + tmp.next = newNode; + } + size++; + + } + + private void checkMinBound(int index) { + if (index < 0) { + throw new IllegalArgumentException(); + } + } + + private void checkMaxBound(int index, int max) { + if (index > max) { + throw new IndexOutOfBoundsException(); + } + } + + + public Object get(int index) { + checkMinBound(index); + checkMaxBound(index, size - 1); + Node cur = head; + if (index != 0) { + int pos = 0; + do { + cur = cur.next; + pos++; + } while (pos != index); + } + return cur; + } + + public Object remove(int index) { + checkMinBound(index); + checkMaxBound(index, size - 1); + Node cur = head; + if (index == 0) { + head = cur.next; + } else { + int pos = 1; + Node prev = cur; + while (pos != index) { + prev = prev.next; + pos++; + } + cur = prev.next; + prev.next = cur.next; + } + size--; + return cur; + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + Node newNode = new Node(o, null); + newNode.next = head; + head = newNode; + size++; + } + + public void addLast(Object o) { + Node newNode = new Node(o, null); + if (head == null) { + head = newNode; + } else { + Node tmp = head; + while (tmp.next != null) { + tmp = tmp.next; + } + tmp.next = newNode; + } + size++; + } + + public Object removeFirst() { + if (head == null) { + throw new NoSuchElementException(); + } + Node ret = head; + head = head.next; + size--; + return ret; + } + + public Object removeLast() { + if (head == null) { + throw new NoSuchElementException(); + } + Node ret; + if (head.next == null) { + ret = head; + head = null; + } else { + Node prev = head; + ret = head.next; + while (ret.next != null) { + prev = ret; + ret = ret.next; + } + prev.next = null; + } + size--; + return ret; + } + + public Iterator iterator() { + return null; + } + + + private static class Node { + Object data; + Node next; + + public Node(Object data, Node next) { + this.data = data; + this.next = 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() { + + } + + /** + * 从第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/group23/1028361767/Week1DataStructure/src/com/coding/basic/List.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/List.java new file mode 100644 index 0000000000..01398944e6 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/List.java @@ -0,0 +1,13 @@ +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/group23/1028361767/Week1DataStructure/src/com/coding/basic/Queue.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Queue.java new file mode 100644 index 0000000000..bb24e2132e --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Queue.java @@ -0,0 +1,22 @@ +package com.coding.basic; + +public class Queue { + + private LinkedList linkedList = new LinkedList(); + + public void enQueue(Object o) { + linkedList.add(o); + } + + public Object deQueue() { + return linkedList.removeFirst(); + } + + public boolean isEmpty() { + return linkedList.size() == 0; + } + + public int size() { + return linkedList.size(); + } +} diff --git a/group23/1028361767/Week1DataStructure/src/com/coding/basic/Stack.java b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Stack.java new file mode 100644 index 0000000000..55c96985a9 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/com/coding/basic/Stack.java @@ -0,0 +1,35 @@ +package com.coding.basic; + +import java.util.EmptyStackException; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o) { + elementData.add(o); + } + + public Object pop() { + checkBound(); + return elementData.get(size() - 1); + } + + public Object peek() { + checkBound(); + return elementData.remove(size() - 1); + } + + public boolean isEmpty() { + return size() == 0; + } + + public int size() { + return elementData.size(); + } + + private void checkBound() { + if (isEmpty()) { + throw new EmptyStackException(); + } + } +} diff --git a/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestArrayList.java b/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestArrayList.java new file mode 100644 index 0000000000..61562d2a39 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestArrayList.java @@ -0,0 +1,60 @@ +package test.com.coding.basic; + +import com.coding.basic.ArrayList; +import org.junit.Assert; +import org.junit.Test; + +public class TestArrayList { + + @Test + public void testAdd() { + ArrayList list = new ArrayList(); + int i = 0; + for (; i < 1000; i++) { + list.add(new Object()); + } + Assert.assertTrue(list.size() == i); + } + + @Test + public void testGet() { + ArrayList list = new ArrayList(); + int i = 0; + for (; i < 10; i++) { + list.add(new Object()); + } + Assert.assertFalse(list.get(5) == null); + try { + list.get(10); + Assert.assertTrue(false); + } catch (IndexOutOfBoundsException e) { + Assert.assertTrue(true); + } + } + + @Test + public void testAddWithIndex() { + ArrayList list = new ArrayList(); + int i = 0; + for (; i < 10; i++) { + list.add(new Object()); + } + Object obj = list.get(5); + list.add(5, new Object()); + Assert.assertTrue(list.size() == (i + 1)); + Assert.assertTrue(obj == list.get(6)); + } + + @Test + public void testRemove() { + ArrayList list = new ArrayList(); + int i = 0; + for (; i < 10; i++) { + list.add(i); + } + Object tempObj = list.get(5); + Assert.assertTrue(tempObj == list.remove(5)); + Assert.assertTrue(list.size() == (i - 1)); + Assert.assertTrue((int) list.get(list.size() - 1) == (i - 1)); + } +} diff --git a/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestBinaryTreeNode.java b/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestBinaryTreeNode.java new file mode 100644 index 0000000000..a137ceffb8 --- /dev/null +++ b/group23/1028361767/Week1DataStructure/src/test/com/coding/basic/TestBinaryTreeNode.java @@ -0,0 +1,37 @@ +package test.com.coding.basic; + +import com.coding.basic.BinaryTreeNode; +import org.junit.Test; + +public class TestBinaryTreeNode { + + @Test + public void testInsert() { + BinaryTreeNode binaryTree = new BinaryTreeNode(5); + binaryTree.insert(2); + binaryTree.insert(7); + binaryTree.insert(1); + binaryTree.insert(6); + + printNode(binaryTree); + + binaryTree.insert(4); + binaryTree.insert(8); + + System.out.println("*************************"); + printNode(binaryTree); + } + + private void printNode(BinaryTreeNode node) { + System.out.print("node's data is " + node.getDataIntVal()); + System.out.println(" ,node's parent' data is " + (node.getParent() == null ? "null" : node.getParent().getDataIntVal())); + if (node.getLeft() != null) { + System.out.println("find left child node."); + printNode(node.getLeft()); + } + if (node.getRight() != null) { + System.out.println("find right child node."); + printNode(node.getRight()); + } + } +} diff --git a/group23/1072760797-skomefen/day3-19/src/com/coderising/array/ArrayUtil.java b/group23/1072760797-skomefen/day3-19/src/com/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..f1d0af35b9 --- /dev/null +++ b/group23/1072760797-skomefen/day3-19/src/com/coderising/array/ArrayUtil.java @@ -0,0 +1,117 @@ +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[] reverse = new int[origin.length]; + 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"); //密码和预设的不一�? + + + 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/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/DataStructsTest/src/com/coding/datastructs/ArrayUtil.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/DataStructsTest/src/com/coding/datastructs/ArrayUtil.java" new file mode 100644 index 0000000000..ff773dffcc --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/DataStructsTest/src/com/coding/datastructs/ArrayUtil.java" @@ -0,0 +1,141 @@ +/** + * + */ +package com.coding.datastructs; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + + +public class ArrayUtil { + + + public void reverseArray(int[] origin){ + for (int i=0; i temp = new HashSet(); + for(Integer i : newArray) + temp.add(i); + for (int i = 0; i < temp.size(); i++) { + newArray[i]=(int)temp.toArray()[i]; + } + Arrays.sort(Arrays.copyOfRange(newArray, 0, temp.size())); + return Arrays.copyOfRange(newArray, 0, temp.size()); + } + + public int[] grow(int [] oldArray, int size){ + int[] target = new int[oldArray.length+size]; + System.arraycopy(oldArray, 0, target, 0, oldArray.length); + return target; + } + + + public int[] fibonacci(int max){ + ArrayList list = new ArrayList(); + list.add(1); + list.add(1); + if(max<=1){ + return new int[0]; + } + for (int i = 2; i < max; i++) { + int a = list.get(i-1)+list.get(i-2); + if(a list = new ArrayList(); + int j=1; + for(int i=2;i<100;i++){ + j=i; + while(j>0){ + if(i%j==0&&i!=j&&j!=1){ + break; + }else{ + j--; + } + } + if(j==0){ + list.add(i); + } + } + int[] newArray = new int[list.size()]; + for(int i=0;i list = new ArrayList(); + for(int i = 1; i < max; i++) + { + int sum = 0; + for(int j = 1; j < i; j++) + { + if(i % j == 0) + { + sum = sum + j; + } + } + if(sum == i) + { + list.add(i); + } + } + int[] newArray = new int[list.size()]; + for(int i=0;i + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git "a/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/LoginAction.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/LoginAction.java" new file mode 100644 index 0000000000..07d16b45d3 --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/LoginAction.java" @@ -0,0 +1,35 @@ +package com.coderising.litestruts; + + +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/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Struts.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Struts.java" new file mode 100644 index 0000000000..bdcafdff8a --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Struts.java" @@ -0,0 +1,122 @@ +package com.coderising.litestruts; + +import java.io.File; +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; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +public class Struts { + + public static View runAction(String actionName, + Map parameters) { + + + View view = new View(); + Map> array = new HashMap>(); + Map params = new HashMap(); + Map classData = new HashMap(); + try { + analysisXml(classData,array); + Map jspData = array.get(actionName); + String s = "ԲݹactionNameûжӦclass࣬Ҫ´"; + if (!classData.containsKey(actionName)) { + throw new ClassNotFoundException(s); + } + + Class class1 = Class.forName(classData.get(actionName)); + LoginAction login = (LoginAction) class1.newInstance(); + for (String ss : parameters.keySet()) { + Method[] methos1 = class1.getMethods(); + for (int i = 0; i < methos1.length; i++) { + if (("set" + ss.substring(0, 1).toUpperCase() + ss + .substring(1)).equals(methos1[i].getName())) { + methos1[i].invoke(login, parameters.get(ss)); + break; + + } + } + } + + Method method1 = class1.getMethod("execute"); + String result = (String) method1.invoke(login); + if(null!=result){ + view.setJsp(jspData.get(result)); + } + Method[] methos2 = class1.getMethods(); + for (int i = 0; i < methos2.length; i++) { + if(methos2[i].getName().substring(0, 3).equals("get")){ + Object value1 = (Object) (methos2[i].invoke(login)); + String name1 = methos2[i].getName(); + params.put(name1.substring(3, 4).toLowerCase()+name1.substring(4), value1); + } + } + view.setParameters(params); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return view; + } + + + public static void analysisXml(Map xmlData,Map> array) { + try { + + String dirpath = System.getProperty("user.dir"); + String xmlFile = dirpath + "/WebContent/WEB-INF/etc/struts.xml"; + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build(new File(xmlFile)); + Element xRoot = doc.getRootElement(); + List actions = getChildren(xRoot, "action"); + for (int i = 0; i < actions.size(); i++) { + Element e = (Element) actions.get(i); + String actionName1 = getAttributeValue(e, "name"); + String className = getAttributeValue(e, "class"); + xmlData.put(actionName1, className); + List results = getChildren(e, "result"); + Map jspData = new HashMap(); + for (int j = 0; j < results.size(); j++) { + Element result = (Element) results.get(j); + String jspUrl = getValue(result); + String resultName = getAttributeValue(result, "name"); + jspData.put(resultName, jspUrl); + array.put(actionName1, jspData); + } + } + + // /StrutsDemo/WebContent/WEB-INF/etc/struts.xml + } catch (Exception e) { + e.printStackTrace(); + } + } + + + public static Element getChild(Element element, String sonMark) { + return element == null ? null : element.getChild(sonMark); + } + + + public static List getChildren(Element element, String sonMark) { + return element == null ? null : element.getChildren(sonMark); + } + + + public static String getValue(Element element) { + return element == null ? "" : element.getValue(); + } + + + public static String getAttributeValue(Element element, String attribute) { + return element == null ? null : element.getAttributeValue(attribute); + } + +} \ No newline at end of file diff --git "a/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/StrutsTest.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/StrutsTest.java" new file mode 100644 index 0000000000..52f08f3652 --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/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"); //Ԥ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")); + } +} \ No newline at end of file diff --git "a/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Test.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Test.java" new file mode 100644 index 0000000000..d7bcd36d42 --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/Test.java" @@ -0,0 +1,94 @@ +/** + * + */ +package com.coderising.litestruts; + +import java.io.BufferedReader; +import java.io.File; +import java.io.StringReader; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +/** + * Title: + * Description: + * @author HuangLiang + * @201731710:55:39 + * + */ +public class Test { + + /**Description: + * @param args + * @author HuangLiang 2017317 10:55:39 + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + String name1 = "getName"; + System.out.println(name1.substring(3, 4).toLowerCase()+name1.substring(4)); + try { + Class class1 = Class.forName("com.coderising.litestruts.LoginAction"); + Method[] methos1 = class1.getMethods(); + for(int i=0;i para[] = methos1[i].getParameterTypes(); + throw new ClassNotFoundException(); + } + System.out.println(""); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + /** + * ȡXMLӱǩ + * + * @param element + * ǩڵ + * @param sonMark + * ӱǩ + * @return + */ + public static Element getChild(Element element, String sonMark) { + return element == null ? null : element.getChild(sonMark); + } + + /** + * ȡXMLӱǩ + * + * @param element + * ǩڵ + * @param sonMark + * ӱǩ + * @return + */ + public static List getChildren(Element element, String sonMark) { + return element == null ? null : element.getChildren(sonMark); + } + + /** + * s ȡXMLǩֵ + * + * @param element + * @return + */ + public static String getValue(Element element) { + return element == null ? "" : element.getValue(); + } + /** + * s ȡXMLֵ + * + * @param element + * @return + */ + public static String getAttributeValue(Element element, String attribute) { + return element == null ? null : element.getAttributeValue(attribute); + } + +} diff --git "a/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/View.java" "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/src/com/coderising/litestruts/View.java" new file mode 100644 index 0000000000..f68a8c438b --- /dev/null +++ "b/group23/1246614258/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/StrutsDemo/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/group23/609041842/.classpath b/group23/609041842/.classpath new file mode 100644 index 0000000000..4449a3dae9 --- /dev/null +++ b/group23/609041842/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/group23/609041842/.gitignore b/group23/609041842/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group23/609041842/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group23/609041842/.project b/group23/609041842/.project new file mode 100644 index 0000000000..b2b4094e01 --- /dev/null +++ b/group23/609041842/.project @@ -0,0 +1,17 @@ + + + 609041842coding + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group23/609041842/.settings/org.eclipse.jdt.ui.prefs b/group23/609041842/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000000..b6ec1a71fb --- /dev/null +++ b/group23/609041842/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,60 @@ +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_methods=false +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_missing_override_annotations_interface_methods=true +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=false +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_functional_interfaces=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.correct_indentation=false +sp_cleanup.format_source_code=true +sp_cleanup.format_source_code_changes_only=false +sp_cleanup.insert_inferred_type_arguments=false +sp_cleanup.make_local_variable_final=true +sp_cleanup.make_parameters_final=false +sp_cleanup.make_private_fields_final=true +sp_cleanup.make_type_abstract_if_missing_method=false +sp_cleanup.make_variable_declarations_final=false +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=false +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_redundant_type_arguments=true +sp_cleanup.remove_trailing_whitespaces=false +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=false +sp_cleanup.remove_unused_imports=false +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=false +sp_cleanup.sort_members_all=false +sp_cleanup.use_anonymous_class_creation=false +sp_cleanup.use_blocks=false +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_lambda=true +sp_cleanup.use_parentheses_in_expressions=false +sp_cleanup.use_this_for_non_static_field_access=false +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true +sp_cleanup.use_this_for_non_static_method_access=false +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true +sp_cleanup.use_type_arguments=false diff --git a/group23/609041842/src/com/homework01/ArrayList.java b/group23/609041842/src/com/homework01/ArrayList.java new file mode 100644 index 0000000000..1feb6162ad --- /dev/null +++ b/group23/609041842/src/com/homework01/ArrayList.java @@ -0,0 +1,49 @@ +package com.homework01; + +import java.util.Arrays; + +public class ArrayList { + + private Object[] obj = new Object[0]; + + public void add(Object o) { + Object[] tar = new Object[obj.length + 1]; + System.arraycopy(obj, 0, tar, 0, obj.length); + tar[tar.length - 1] = o; + obj = tar; + System.out.println(Arrays.toString(obj)); + } + + public void add(int index, Object o) { + Object[] tar = new Object[obj.length + 1]; + System.arraycopy(obj, 0, tar, 0, index); + tar[index] = o; + System.arraycopy(obj, index, tar, index + 1, obj.length - index); + obj = tar; + } + + public Object get(int index) { + return obj[index]; + } + + public int size(){ + return obj.length; + } + + public Object remove(int index){ + Object[] tar = new Object[obj.length-1]; + System.arraycopy(obj, 0, tar, 0, index); + System.arraycopy(obj, index+1, tar, index, obj.length-index-1); + Object o = obj[index]; + obj = tar; + return o;//���ر�ɾԪ�� + } + public static void main(String[] args) { + ArrayList al = new ArrayList(); + al.add("hello"); + al.add("java"); + al.add(2, "addm"); + System.out.println(al.remove(1)); + } + +} diff --git a/group23/609041842/src/com/homework01/LinkedList.java b/group23/609041842/src/com/homework01/LinkedList.java new file mode 100644 index 0000000000..f18c110c7c --- /dev/null +++ b/group23/609041842/src/com/homework01/LinkedList.java @@ -0,0 +1,87 @@ +package com.homework01; + +public class LinkedList { + private static Node head; + private Node last; + public int size; + + public void add(Object o) { + Node l = last; + Node newNode = new Node(l, o, null); + last = newNode; + if (head == null) { + head = newNode; + size = 1; + } else { + l.next = newNode; + size++; + } + } + + public void add(int index, Object o) { + Node n = node(index); + System.out.println(n.data); + Node pred = n.prev; + Node newNode = new Node(pred, o, n); + if (pred == null) { + head = newNode; + } else { + pred.next = newNode; + } + size++; + } + + + public Node get(int index){ + return node(index); + } + public Node node(int index) { + Node n = head; + for (int i = 0; i < index; i++) { + n = n.next; + } + return n; + } + + public Node remove(int index){ + Node del = node(index); + Node after = del.next; + Node before = del.prev; + before.next = after; + after.prev = before; + size--; + return del; + } + private static class Node { + Node next; + Object data; + Node prev; + + private Node(Node prev, Object data, Node next) { + this.data = data; + this.next = next; + this.prev = prev; + } + } + + public static void main(String[] arg) { + LinkedList ll = new LinkedList(); + ll.add("hello"); + ll.add("java"); + ll.add("jvm"); + ll.add("jvmd"); + // System.out.println(ll.get(2)); +// ll.add(1, "ds"); + System.out.println(ll.get(0).data); + System.out.println(ll.get(1).data); + System.out.println(ll.get(2).data); + System.out.println(ll.get(3).data); + System.out.println(ll.size); + System.out.println(ll.remove(1).data); + System.out.println(ll.get(0).data); + System.out.println(ll.get(1).data); + System.out.println(ll.get(2).data); + System.out.println(ll.size); + } + +} diff --git a/group23/609041842/src/com/homework01/Queue.java b/group23/609041842/src/com/homework01/Queue.java new file mode 100644 index 0000000000..afc54a2dda --- /dev/null +++ b/group23/609041842/src/com/homework01/Queue.java @@ -0,0 +1,17 @@ +package com.homework01; + +public class Queue { + + private LinkedList lk = new LinkedList(); + public void enQueue(Object o){ + lk.add(o); + } + public void deQueue(){ + lk.remove(lk.size-1); + } + public boolean isEmpty(){ + if(lk.size == 0) + return true; + return false; + } +} diff --git a/group23/609041842/src/com/homework01/Stack.java b/group23/609041842/src/com/homework01/Stack.java new file mode 100644 index 0000000000..a5bc4488af --- /dev/null +++ b/group23/609041842/src/com/homework01/Stack.java @@ -0,0 +1,30 @@ +package com.homework01; + +public class Stack { + + private ArrayList array = new ArrayList(); + + public void push(Object o){ + array.add(o); + } + public Object pop(){ + return array.remove(array.size()-1); + } + + public boolean isEmpty(){ + if(array.size()<=0) + return true; + return false; + } + + public int size(){ + return array.size(); + } + public static void main(String[] args) { + Stack sc = new Stack(); + sc.push("hello world"); + sc.push("java"); + sc.push("jvm"); + } + +} diff --git a/group23/609041842/src/test.java b/group23/609041842/src/test.java new file mode 100644 index 0000000000..931a307711 --- /dev/null +++ b/group23/609041842/src/test.java @@ -0,0 +1,9 @@ +import org.junit.Test; + +public class test { + + @Test + public void test(){ + System.out.println("Heool"); + } +} diff --git a/group23/632678665/com/basic/week2/datastructure/ArrayTest.java b/group23/632678665/com/basic/week2/datastructure/ArrayTest.java new file mode 100644 index 0000000000..46c3f8b601 --- /dev/null +++ b/group23/632678665/com/basic/week2/datastructure/ArrayTest.java @@ -0,0 +1,50 @@ +package com.basic.week2.datastructure; + +import static org.junit.Assert.*; + +import java.util.Arrays; + +import org.junit.Test; + +public class ArrayTest { + private ArrayUtil t=new ArrayUtil(); + @Test + public void testReverseArray(){ + int [] data1={7, 9 , 30, 3}; + int [] data2={7, 9, 30, 3, 4}; + t.reverseArray(data2); + } + @Test + public void testRemoveZero(){ + int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; + System.out.println(Arrays.toString(t.removeZero(oldArr))); + } + @Test + public void testMerge(){ + int [] a1 = {3, 5, 7,8}; + int [] a2 = {4, 5, 6,7}; + System.out.println(Arrays.toString(t.merge(a1, a2))); + } + @Test + public void testGrow(){ + int [] oldArray = {2,3,6}; + System.out.println(Arrays.toString(t.grow(oldArray, 5))); + } + @Test + public void testFibonacci(){ + System.out.println(Arrays.toString(t.fibonacci(1))); + } + @Test + public void testGetPrimes(){ + System.out.println(Arrays.toString(t.getPrimes(23))); + } + @Test + public void testGetPerfectNumbers(){ + System.out.println(Arrays.toString(t.getPerfectNumbers(7))); + } + @Test + public void testJoin(){ + int [] array= {3,8,9}; + System.out.println(t.join(array, "-")); + } +} diff --git a/group23/632678665/com/basic/week2/datastructure/ArrayUtil.java b/group23/632678665/com/basic/week2/datastructure/ArrayUtil.java new file mode 100644 index 0000000000..10089c1b3a --- /dev/null +++ b/group23/632678665/com/basic/week2/datastructure/ArrayUtil.java @@ -0,0 +1,228 @@ +package com.basic.week2.datastructure; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.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 index=(int) (origin.length/2); + for(int i=0;iarray=new ArrayList (); + int from; + int to; + for(int i=0;i list=new ArrayList(); + for(int i=0;i set=new HashSet(); + set.addAll(list); + Object[] array=set.toArray(); + int [] arrayInt=new int [array.length]; + for(int i=0;ilist=new ArrayList(); + list.add(front); + list.add(behind); + while(true){ + result=front+behind; + if(max list=new ArrayList(); + int num=3; + list.add(2); + boolean flag=true; + while(true){ + flag=true; + for(int i=2;i list=new ArrayList(); + Set temp=new HashSet(); + int num=1; + int result=0; + while(true){ + for(int i=1;imax){ + break; + } + if(num==result){ + list.add(num); + } + temp.clear(); + result=0; + num++; + } + int [] array=new int [list.size()]; + for(int i=0;i list=new ArrayList(); + for(int i=0;i + + + + + + + + diff --git a/group23/729693763/Second_Homework2/.project b/group23/729693763/Second_Homework2/.project new file mode 100644 index 0000000000..fb7175dae6 --- /dev/null +++ b/group23/729693763/Second_Homework2/.project @@ -0,0 +1,17 @@ + + + Second_Homework2 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group23/729693763/Second_Homework2/.settings/org.eclipse.jdt.core.prefs b/group23/729693763/Second_Homework2/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..3a21537071 --- /dev/null +++ b/group23/729693763/Second_Homework2/.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/group23/729693763/Second_Homework2/src/com/danny/hw2/ArrayUtil.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/ArrayUtil.java new file mode 100644 index 0000000000..af11509593 --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/ArrayUtil.java @@ -0,0 +1,221 @@ +package com.danny.hw2; + +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) { + int size = origin.length; + int[] temp = new int[size]; + + for(int i=0;i < size; i++){ + temp[i] = origin[size-i-1]; + } + + for(int i=0;i array2[index2] ){ + result[resultIndex++] = array2[index2++]; + break; + } + } else{ + result[resultIndex++] = array1[index1++]; + } + } + System.out.println(resultIndex); + return Arrays.copyOf(result, resultIndex); + + } + + /** + * 把一个已经存满数据的数组 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 oldSize = oldArray.length; + int[] newArray= new int[oldSize+size]; + + for ( int i = 0; i < newArray.length; i++) { + if ( i < oldSize ) { + newArray[i] = oldArray[i]; + } else{ + newArray[i] = 0; + } + } + 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[0]; + } + + int maxIndex = 1000; + int realIndex = 0; + int[] array=new int[maxIndex]; + for (; realIndex <= array.length; realIndex++) { + int fibonacciNum = getFibonacciArray(realIndex+1); + if(fibonacciNum > max){ + break; + } + array[realIndex] = fibonacciNum; + } + + + + return Arrays.copyOf(array, realIndex); + } + + + private int getFibonacciArray(int index){ + + if(index == 0 || index == 1){ + return index; + } + return getFibonacciArray(index - 1) + getFibonacciArray(index - 2); + } + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + int maxIndex = 1000; + int realSize = 0; + int[] array = new int[maxIndex]; + for (int i = 0; i < max; i++) { + if(isPrimers(i)){ + array[realSize++] = i; + } + } + return Arrays.copyOf(array, realSize); + } + private static boolean isPrimers(int n){ + if (n <= 3) { + return n > 1; + } + + for(int i=2;i<=Math.sqrt(n);i++){ + if(n%i == 0) + return false; + } + return true; + } + + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int maxIndex = 1000; + int realIndex = 0; + int[] array = new int[maxIndex]; + int sum = 0; + + for (int i = 1; i < max /2 +1; i++) { + if(max % i == 0){ + sum += i; + array[realIndex++] = i; + } + } + if(sum == max){ + return Arrays.copyOf(array, realIndex); + }else{ + return new int[0]; + } + + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) { + String result=""; + for (int i = 0; i < array.length; i++) { + result+= String.valueOf(array[i]) + seperator; + } + //去掉多余的一个seperator + return result.substring(0, result.length()-1); + } + + + + +} diff --git a/group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java new file mode 100644 index 0000000000..340d542dec --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java @@ -0,0 +1,39 @@ +package com.danny.hw2; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @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/group23/729693763/Second_Homework2/src/com/danny/hw2/Struts.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/Struts.java new file mode 100644 index 0000000000..6e1cb4ba96 --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/Struts.java @@ -0,0 +1,163 @@ +package com.danny.hw2; + +import java.io.File; +import java.lang.invoke.CallSite; +import java.lang.reflect.Constructor; +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.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import org.jaxen.*; + +public class Struts { + + private static Document file = null; + private static String file_path = + new File("").getAbsolutePath()+".\\xmlFolder\\struts.xml"; + + private static String viewPath="com.danny.hw2.View"; + + //0. 读取配置文件struts.xml + private static Document parse(String path){ + SAXReader reader = new SAXReader(); + Document document = null; + try { + document = reader.read(path); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return document; + } + + private static Element getAction(Document document,String name){ + + List lElement = (List) file.selectObject("/struts/action"); + Element actionElement = null; + for(Element e:lElement){ + if(e.attributeValue("name").equals(name)){ + actionElement = e; + break; + } + } + return actionElement; + } + + public static View runAction(String actionName, Map parameters) { + + file = parse(file_path); + + //返回的class View; + Object viewClass = null; + + + //0 Get Action Element + Element actionElement = getAction(file, actionName); + + + String actionClassPath = actionElement.attributeValue("class"); + System.out.println(actionClassPath); + + Object action = null; + + try { + /* + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + */ + action = Class.forName(actionClassPath).newInstance(); + + Method setName = action.getClass().getMethod("setName",String.class); + setName.invoke(action, parameters.get("name")); + + Method setPassword = action.getClass().getMethod("setPassword",String.class); + setPassword.invoke(action, parameters.get("password")); + + + //2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + Method execute = action.getClass().getMethod("execute", null); + Object status = execute.invoke(action); + + System.out.println(status.toString()); + + + //3获得所有的Getter字段 + Field[] files = action.getClass().getDeclaredFields(); + + HashMap save = new HashMap<>(); + + //找到需要的数据,线存到save中 + for (int i = 0; i < files.length; i++) { + String name = files[i].getName(); + name = "get" + name.substring(0,1).toUpperCase() + + name.substring(1); + + + Method getter = action.getClass().getMethod(name,null); + save.put(files[i].getName(), (String) getter.invoke(action)); + + } + //塞进viewClass里面 + viewClass = Class.forName(viewPath).newInstance(); + Method setParameters = viewClass.getClass().getMethod("setParameters", Map.class); + setParameters.invoke(viewClass, save); + + + + //4将jsp放进去 + List resultElement = actionElement.selectNodes("result"); + for(Element e:resultElement){ + if(e.attributeValue("name").equals(status.toString())){ + String jspFields= e.getStringValue(); + viewClass.getClass().getMethod("setJsp", String.class). + invoke(viewClass, jspFields); + } + + } + + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + + throw new RuntimeException(e.getMessage()); + } + + + + + /* + + 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) viewClass; + } + + +} diff --git a/group23/729693763/Second_Homework2/src/com/danny/hw2/View.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/View.java new file mode 100644 index 0000000000..67ff0a061b --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/View.java @@ -0,0 +1,23 @@ +package com.danny.hw2; + +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/group23/729693763/Second_Homework2/src/com/danny/hw2/test/ArrayUtilTest.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/test/ArrayUtilTest.java new file mode 100644 index 0000000000..a7fce5320a --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/test/ArrayUtilTest.java @@ -0,0 +1,95 @@ +package com.danny.hw2.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.danny.hw2.ArrayUtil; + +public class ArrayUtilTest { + + @Test + public void testReverseArray() { +// * 给定一个整形数组a , 对该数组的值进行置换 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] 如果 a = +// * [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + int[] testData = new int[]{7,9,30,3}; + int[] ans = new int[]{3,30,9,7}; + new ArrayUtil().reverseArray(testData); + + for (int i = 0; i < ans.length; i++) { + assertEquals(ans[i], testData[i]); + } + } + + @Test + public void testRemoveZero() { + int[] testData = new int[]{1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; + int[] ans = new int[]{1,3,4,5,6,6,5,4,7,6,7,5}; + + int[] test = new ArrayUtil().removeZero(testData); + for (int i = 0; i < ans.length; i++) { + assertEquals(ans[i], test[i]); + } + } + + @Test + public void testMerge() { +// * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 例如 a1 = +// * [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + int[] a1 = new int[]{3, 5, 7,8}; + int[] a2 = new int[]{4,5,6,7}; + + int[] ans = new int[]{3,4,5,6,7,8}; + + int[] test = new ArrayUtil().merge(a1, a2); + + for (int i = 0; i < test.length; i++) { + assertEquals(ans[i], test[i]); + } + + } + + @Test + public void testGrow() { +// 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size +// * 注意,老数组的元素在新数组中需要保持 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 +// * [2,3,6,0,0,0] + + int size = 3; + int[] testData = new int[]{2,3,6}; + int[] test = new ArrayUtil().grow(testData, size); + assertEquals(testData.length+size, test.length); + + } + + @Test + public void testFibonacci() { + int[] ans = new int[]{1,1,2,3,5,8,13}; + int[] array = new ArrayUtil().fibonacci(15); + for (int i = 0; i < ans.length; i++) { + assertEquals(ans[i], array[i]); + } + + } + + @Test + public void testGetPerfectNumbers() { + + int[] ans=new int[]{1,2,4,7,14}; + int[] array=new ArrayUtil().getPerfectNumbers(28); + for (int i = 0; i < array.length; i++) { + assertEquals(ans[i], array[i]); + } + } + + @Test + public void testJoin() { + //* 用seperator 把数组 array给连接起来 例如array= [3,8,9], + //seperator = "-" 则返回值为"3-8-9" + int[] test = new int[]{3,8,9}; + + String test1 = new ArrayUtil().join(test, "-"); + assertEquals("3-8-9", test1); + } + +} diff --git a/group23/729693763/Second_Homework2/src/com/danny/hw2/test/StrutsTest.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/test/StrutsTest.java new file mode 100644 index 0000000000..49b770f015 --- /dev/null +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/test/StrutsTest.java @@ -0,0 +1,46 @@ +package com.danny.hw2.test; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +import com.danny.hw2.Struts; +import com.danny.hw2.View; + + + + + +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/group23/729693763/Second_Homework2/xmlFolder/struts.xml b/group23/729693763/Second_Homework2/xmlFolder/struts.xml new file mode 100644 index 0000000000..8a788e9b1f --- /dev/null +++ b/group23/729693763/Second_Homework2/xmlFolder/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/group23/729693763/readme.md b/group23/729693763/readme.md index c1f8e02e42..7e7fac06ae 100644 --- a/group23/729693763/readme.md +++ b/group23/729693763/readme.md @@ -1,4 +1,11 @@ Data Struct contain: ArrayList, LinkedList, BinaryTreeNode, Stack, Queue, Iterator +<<<<<<< HEAD --- --- Add Blog link: http://www.cnblogs.com/CodeSaveMe/p/6523745.html +======= +--- --- +Add Blog link: http://www.cnblogs.com/CodeSaveMe/p/6523745.html + +Add week2 Blog link:http://www.cnblogs.com/CodeSaveMe/p/6571621.html +>>>>>>> my diff --git a/group23/769232552/coding/pom.xml b/group23/769232552/coding/pom.xml new file mode 100644 index 0000000000..5b9701ed4d --- /dev/null +++ b/group23/769232552/coding/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + com.coding + coding2017 + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + + + + + ch.qos.logback + logback-classic + 1.1.1 + + + dom4j + dom4j + 1.6.1 + + + junit + junit + 4.12 + test + + + commons-lang + commons-lang + 2.6 + + + + \ No newline at end of file diff --git a/group23/769232552/coding/src/main/java/code01/ArrayList.java b/group23/769232552/coding/src/main/java/code01/ArrayList.java new file mode 100644 index 0000000000..6746de2a50 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/ArrayList.java @@ -0,0 +1,138 @@ +package code01; + +/** + * Created by yaoyuan on 2017/3/6. + */ +public class ArrayList implements List { + + private int max_size = 0;//总长度 + private int current_size = 0; //当前长度 + private float extendPercent = 2; //扩展系数 + + private Object[] elementData; + + /** + * 默认构造函数,初始化数组长度为100 + */ + public ArrayList(){ + this.elementData = new Object[100]; + this.max_size = 100; + } + /** + * 构造函数 + * @param size,初始化数组长度 + */ + public ArrayList(int size){ + this.elementData = new Object[size]; + this.max_size = size; + } + + /** + * 顺序添加元素,超出原始界限时,数组自动扩展 + */ + public void add(Object o) { + //如果越界了,需要复制原有的数组到扩充后的数组中 + if(this.current_size + 1 > this.max_size) { + this.max_size = (int) Math.floor(this.max_size * this.extendPercent); + this.elementData = copyToNew(this.elementData,this.max_size); + } + this.elementData[this.current_size] = o; + this.current_size ++; + + } + + /** + * 指定位置添加元素 + * 一种是在中间,一种是当前插入的位置尾部(如果超过尾部则默认添加到尾部) + */ + public void add(int index, Object o){ + assert(index>=0); + //如果越界了,需要复制原有的数组到扩充后的数组中 + if(this.current_size + 1 > this.max_size) { + //如果越界了,需要复制原有的数组到扩充后的数组中 + this.max_size = (int) Math.floor(this.max_size * this.extendPercent); + this.elementData = copyToNew(this.elementData,this.max_size); + } + //数组中间插入 + if(index < this.current_size){ + //需要把当前位置的元素往后移动 + for (int i = this.current_size - 1; i >= index; i--) { + this.elementData[i+1] = this.elementData[i]; + } + this.elementData[index] = o; + }else { + //后面加入 + this.elementData[this.current_size] = o; + } + this.current_size ++; + } + + public Object get(int index){ + if(index >= 0 && index <= this.current_size-1){ + return this.elementData[index]; + }else { + throw new ArrayIndexOutOfBoundsException(index); + } + } + + /** + * 删除指定位置的元素 + * @param index + * @return + */ + public Object remove(int index){ + Object result = null; + if(index >= 0 && index <= current_size-1){ + result = elementData[index]; + //删除操作 + if(index == current_size - 1){ + elementData[index] = null; + }else { + //需要把当前位置后面的元素往前移动 + for (int i = index; i < this.current_size-1 ; i++) { + this.elementData[i] = this.elementData[i+1]; + } + this.elementData[this.current_size-1] = null; + } + this.current_size --; + }else { + throw new ArrayIndexOutOfBoundsException(index); + } + return result; + } + + public int size(){ + return this.current_size; + } + + public Iterator iterator(){ + return new Iterator() { + int next_pos = 0; + int pos = -1; + public boolean hasNext() { + if(max_size <= 0){ + return false; + } + return next_pos < ArrayList.this.size(); + } + + public Object next() { + Object next = ArrayList.this.get(next_pos); + pos = next_pos ++; + return next; + } + public void remove(){ + ArrayList.this.remove(pos); + } + }; + } + + private Object[] copyToNew(Object[] oldArray, int extendSize){ + Object[] newArray = new Object[extendSize]; + for (int i = 0; i < size(); i++) { + newArray[i] = oldArray[i]; + } + return newArray; + } + +} \ No newline at end of file diff --git a/group23/769232552/coding/src/main/java/code01/BinaryTree.java b/group23/769232552/coding/src/main/java/code01/BinaryTree.java new file mode 100644 index 0000000000..b29fb960cb --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/BinaryTree.java @@ -0,0 +1,97 @@ +package code01; + +/** + * Created by yaoyuan on 2017/3/10. + */ +public class BinaryTree>{ + + private BinaryTreeNode root = null; + private int size = 0; + + public BinaryTreeNode createBinaryTree(T[] array){ + for(T data : array){ + this.insert(data); + } + return this.root; + } + + // recursive way, + // t is the node that roots the subtree. + public BinaryTreeNode insert(T data, BinaryTreeNode t){ + if(t == null){ + return new BinaryTreeNode(data); + } + int comparator = ((T) t.data).compareTo(data); + if(comparator > 0){ + t.left = insert(data,t.right); + }else if(comparator < 0){ + t.right = insert(data,t.left); + }else { + // do nothing + } + return t; + + } + + + //loop way + public void insert(T data){ + if(this.root == null){ + BinaryTreeNode node = new BinaryTreeNode(data); + this.root = node; + this.size ++; + return; + } + BinaryTreeNode cursor = this.root; + while (cursor != null){ + if(data.compareTo((T) cursor.data) <= 0){ + if(cursor.left == null) { + cursor.left = new BinaryTreeNode(data); + return; + } + cursor = cursor.left; + } + if(data.compareTo((T) cursor.data) > 0){ + if(cursor.right == null) { + cursor.right = new BinaryTreeNode(data); + return; + } + cursor = cursor.right; + } + } + this.size ++; + } + + public void leftOrderScan(BinaryTreeNode cursor){ + if(cursor == null){ + return; + } + leftOrderScan(cursor.left); + System.out.println(cursor.data.toString() + " "); + leftOrderScan(cursor.right); + } + + public BinaryTreeNode getRoot(){ + return this.root; + } + + class BinaryTreeNode { + + private T data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public BinaryTreeNode(T data, BinaryTreeNode left, BinaryTreeNode right) { + this.left = right; + this.right = left; + this.data = data; + } + + public BinaryTreeNode(T data) { + this.left = null; + this.right = null; + this.data = data; + } + + } +} diff --git a/group13/1274639949/lesson01/src/com/hans/Iterator.java b/group23/769232552/coding/src/main/java/code01/Iterator.java similarity index 84% rename from group13/1274639949/lesson01/src/com/hans/Iterator.java rename to group23/769232552/coding/src/main/java/code01/Iterator.java index 4ec870ed01..b4074067bb 100644 --- a/group13/1274639949/lesson01/src/com/hans/Iterator.java +++ b/group23/769232552/coding/src/main/java/code01/Iterator.java @@ -1,8 +1,7 @@ -package com.hans; +package code01; public interface Iterator { public boolean hasNext(); public Object next(); public void remove(); } - diff --git a/group23/769232552/coding/src/main/java/code01/LinkedList.java b/group23/769232552/coding/src/main/java/code01/LinkedList.java new file mode 100644 index 0000000000..f7bbc970a9 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/LinkedList.java @@ -0,0 +1,327 @@ +package code01; + + +public class LinkedList implements List { + + private Node head; + private Node tail; //指向链表最后一个元素的引用 + + private int size; //总长度 + + public LinkedList() { + this.head = null; + this.tail = null; + this.size = 0; + } + + /** + * 新增顺序添加一个元素 + * @param o + */ + public void add(Object o){ + Node node = new Node(); + node.data = o; + node.next = null; + //空链表 + if(head == null){ + this.head = node; + this.tail = node; + }else { //非空链表,要先找到链表尾部,再加入新解答 + this.tail.next = node; + this.tail = node; + } + this.size ++; + } + + /** + * 指定索引处添加node + */ + public void add(int index, Object o) { + assert(index >= 0); + Node node = new Node(); + node.data = o; + node.next = null; + + if(index == 0){ + //添加在头部 + node.next = head; + head = node; + }else if(index >= this.size){ + //添加在尾部 + this.tail.next = node; + }else { + //添加在中间 + Node cursor = this.head; + for (int i = 0; i < index - 1; i++) { + cursor = cursor.next; + } + node.next = cursor.next; + cursor.next = node; + } + this.size ++; + } + + public Object get(int index){ + assert(index < this.size); + Node cursor = this.head; + for (int i = 0; i < index; i++) { + cursor = cursor.next; + } + return cursor.data; + } + + public Object remove(int index){ + assert(index >= 0 && index < this.size); + Object result = null; + //删除的是链表尾部的元素 + if(index == this.size - 1){ + Node cursor = this.head; + for (int i = 0; i < index - 1; i++) { + cursor = cursor.next; + } + result = cursor.next.data; + tail = cursor; + cursor.next = null; + }else if(index == 0){ + //删除的是头部元素 + result = head.data; + head = head.next; + }else { + //删除的是链表中间的元素 + Node cursor = this.head; + for (int i = 0; i < index - 1; i++) { + cursor = cursor.next; + } + result = cursor.next.data; + cursor.next = cursor.next.next; + } + this.size --; + return result; + } + + public int size(){ + return this.size; + } + + public void addFirst(Object o){ + Node node = new Node(); + node.data = o; + node.next = null; + if(this.head == null){ + this.head = node; + this.tail = node; + }else { + node.next = head; + this.head = node; + } + this.size ++; + } + public void addLast(Object o){ + Node node = new Node(); + node.data = o; + node.next = null; + if(this.head == null){ + this.head = node; + this.tail = node; + }else { + this.tail.next = node; + this.tail = node; + } + this.size ++; + } + + public Object removeFirst(){ + Object first = null; + if(this.head != null){ + first = this.head.data; + head = head.next; + this.size --; + } + return first; + } + + public Object removeLast(){ + Object last = null; + if(this.tail != null){ + if(this.head != this.tail){ + Node cursor; + for (cursor = head;cursor.next!=tail;cursor=cursor.next); + last = this.tail.data; + this.tail = cursor; + this.tail.next = null; + }else { + last = this.tail.data; + this.head = null; + this.tail = null; + } + this.size --; + } + return last; + } + public Iterator iterator(){ + return null; + } + + /** + * 节点类 + */ + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if(this.head == null || this.head == this.tail){ + return; + } + + Node pre_cursor = null; + Node cursor = this.head; + Node after_cursor = cursor.next; + + while(cursor != null){ + cursor.next = pre_cursor; + pre_cursor = cursor; + cursor = after_cursor; + if(after_cursor != null){ + after_cursor = after_cursor.next; + } + } + + Node tmpNode = this.head; + this.head = this.tail; + this.tail = tmpNode; + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + if(this.head == null || this.head.next == null){ + return; + } + if(this.head.next.next == null){ + this.head = this.head.next; + } + + Node stepOne = this.head; + Node stepTwo = this.head; + + while (stepTwo.next != null){ + stepOne = stepOne.next; + stepTwo = stepTwo.next.next; + } + this.head = stepOne; + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + Node current = head; + Node firstHalf = null; + for (int k = 0; k < i; k ++){ + if(current == null){ + return; + } + firstHalf = current; //记录待删除节点的前一个节点 + current = current.next; + } + + //移动length长度 + for (int j = 0; j < length; j++) { + if(current == null){ + return; + } + current = current.next; + } + + if(i == 0){ + head = current; + }else { + firstHalf.next = current; + } + } + /** + * 假定当前链表和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(){ + if(this.head == null){ + return; + } + Node current = this.head; + Node current_next = this.head; + while (current_next != null){ + current_next = current_next.next; //如果放到下个while循环后面写,就需要判断一次current_next是不是null了 + while(current_next != null && current_next.data.equals(current.data)){ + //删除重复节点 + current.next = current_next.next; + current_next = current_next.next; + } + current = current_next; + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于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; + } + + /** + * 遍历列表 + */ + public void printList(){ + System.out.println(); + for (Node cursor = this.head;cursor!=null;cursor=cursor.next){ + System.out.print(cursor.data+" "); + } + } +} diff --git a/group23/769232552/coding/src/main/java/code01/List.java b/group23/769232552/coding/src/main/java/code01/List.java new file mode 100644 index 0000000000..95bc37d172 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/List.java @@ -0,0 +1,9 @@ +package code01; + +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/group23/769232552/coding/src/main/java/code01/Queue.java b/group23/769232552/coding/src/main/java/code01/Queue.java new file mode 100644 index 0000000000..d9956deb9a --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/Queue.java @@ -0,0 +1,24 @@ +package code01; + +public class Queue { + + private LinkedList linkedList = new LinkedList(); + + public void enQueue(Object o){ + linkedList.addFirst(o); + } + + public Object deQueue(){ + Object result = linkedList.removeLast(); + return result; + } + + public boolean isEmpty(){ + return linkedList.size() == 0; + } + + public int size(){ + return linkedList.size(); + } + +} diff --git a/group13/1274639949/lesson01/src/com/hans/Stack.java b/group23/769232552/coding/src/main/java/code01/Stack.java similarity index 53% rename from group13/1274639949/lesson01/src/com/hans/Stack.java rename to group23/769232552/coding/src/main/java/code01/Stack.java index d370221f1a..dbaeb91a48 100644 --- a/group13/1274639949/lesson01/src/com/hans/Stack.java +++ b/group23/769232552/coding/src/main/java/code01/Stack.java @@ -1,4 +1,4 @@ -package com.hans; +package code01; public class Stack { private ArrayList elementData = new ArrayList(); @@ -8,17 +8,19 @@ public void push(Object o){ } public Object pop(){ - if(elementData.size() <= 0){ - return null; + Object result = null; + if(elementData.size()!=0) { + result = elementData.remove(elementData.size() - 1); } - return elementData.remove(elementData.size() - 1); + return result; } public Object peek(){ - if(elementData.size() <= 0){ - return null; + Object result = null; + if(elementData.size()!=0) { + result = elementData.get(elementData.size() - 1); } - return elementData.get(elementData.size() - 1); + return result; } public boolean isEmpty(){ return elementData.size() == 0; @@ -27,4 +29,3 @@ public int size(){ return elementData.size(); } } - diff --git a/group23/769232552/coding/src/main/java/code02/ArrayUtil.java b/group23/769232552/coding/src/main/java/code02/ArrayUtil.java new file mode 100644 index 0000000000..23055ef138 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/ArrayUtil.java @@ -0,0 +1,257 @@ +package code02; +import org.apache.commons.lang.ArrayUtils; +import java.util.ArrayList; +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){ + if (origin == null || origin.length <= 1){ + return; + } + + int head = 0; + int tail = origin.length - 1; + int tmp; + while (head != tail){ + //调换位置 + tmp = origin[head]; + origin[head] = origin[tail]; + origin[tail] = tmp; + + head ++; + tail --; + } + + } + + /** + * 现在有如下的一个数组: 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 || oldArray.length < 1){ + return null; + } + + List newList = new ArrayList(); + for(int number : oldArray){ + if(number != 0){ + newList.add(number); + } + } + + Integer[] result = new Integer[newList.size()]; + result = (Integer[]) newList.toArray(result); + return ArrayUtils.toPrimitive(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){ + if(array1 == null && array2 == null){ + return null; + } + if(array1 == null){ + return array2; + } + if(array2 == null){ + return array1; + } + int[] newArray = new int[array1.length + array2.length]; + int m = 0,n = 0, k = 0; + while (m < array1.length && n < array2.length){ + if(array1[m] <= array2[n]){ + newArray[k++] = array1[m++]; + }else { + newArray[k++] = array2[n++]; + } + } + if(m >= array1.length){ + while (n < array2.length){ + newArray[k++] = array2[n++]; + } + } + if(n >= array2.length){ + while (m < array1.length){ + newArray[k++] = array1[m++]; + } + } + 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]; + int i = 0; + for (; i < oldArray.length; i++) { + newArray[i] = oldArray[i]; + } + for (int j = 0; j < size; j++){ + newArray[i++] = 0; + } + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + //也就是需要生成一个小于max值的fibonacci数组 + public int[] fibonacci(int max){ + if(max < 2){ + return new int[]{}; + } + if(max < 3){ + return new int[]{1,1}; + } + List list = new ArrayList(); + list.add(0,1); + list.add(1,1); + int i=0; + while (list.get(i) + list.get(i+1) < max){ + list.add(i+2,list.get(i) + list.get(i+1)); + i++; + } + + int[] newArray = new int[list.size()]; + for (int j = 0; j < list.size(); j++) { + newArray[j] = list.get(j).intValue(); + } + return newArray; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + * + * 原理: + * 1,判断一个数字是否为素数,一个数 n 如果是合数,那么它的所有的因子不超过sqrt(n) + * 2,当i是素数的时候,i的所有的倍数必然是合数。 + */ + public int[] getPrimes(int max){ + + if(max <= 2){ + return null; + } + boolean[] prime = new boolean[max + 1]; + for (int i = 2; i <= max; i++) { + if(i%2 == 0){ + prime[i] = false; //偶数 + }else { + prime[i] = true; + } + } + + for (int i = 2; i <= Math.sqrt(max) ; i++) { + if(prime[i]){//奇数 + //如果i是素数,那么把i的倍数标记为非素数 + for(int j = i+i; j <= max; j += i){ + prime[j] = false; + } + } + } + + List num = new ArrayList(); + for (int i = 2; i <= max; i++) { + if(prime[i]){ + num.add(i); + } + } + + Integer[] result = new Integer[num.size()]; + result = (Integer[]) num.toArray(result); + return ArrayUtils.toPrimitive(result); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + + if(max < 6){ + return null; + } + + List perfectNumlist = new ArrayList(); + + for (int j = 6;j <= max; j++){ + List factorNumlist = new ArrayList(); + factorNumlist.add(1); + for (int i = 2; i < j; i++) { + if(j % i == 0){ + factorNumlist.add(i); + } + } + int sum = 0; + for(Integer num : factorNumlist){ + sum += num; + } + + if(sum == j){ + perfectNumlist.add(j); + } + } + Integer[] result = new Integer[perfectNumlist.size()]; + result = (Integer[]) perfectNumlist.toArray(result); + return ArrayUtils.toPrimitive(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(); + } + + public void printArr(int[] array){ + for(int num : array){ + System.out.print(num + " "); + } + } + +} diff --git a/group23/769232552/coding/src/main/java/code02/litestruts/ActionConfig.java b/group23/769232552/coding/src/main/java/code02/litestruts/ActionConfig.java new file mode 100644 index 0000000000..b5e077e7a5 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/ActionConfig.java @@ -0,0 +1,28 @@ +package code02.litestruts; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by yaoyuan on 2017/3/22. + */ +public 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/group23/769232552/coding/src/main/java/code02/litestruts/Configuration.java b/group23/769232552/coding/src/main/java/code02/litestruts/Configuration.java new file mode 100644 index 0000000000..85d3d98a1f --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/Configuration.java @@ -0,0 +1,64 @@ +package code02.litestruts; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.io.File; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Created by yaoyuan on 2017/3/21. + */ +public class Configuration { + + + private String path; + private final Map actionMap = new HashMap(); + + Configuration(String path){ + parseXML(path); + } + + //解析xml文件 + private void parseXML(String path){ + //读取文件 + File file = new File(path); + SAXReader reader = new SAXReader(); + Document document = null; + try { + document = reader.read(file); + } catch (DocumentException e) { + e.printStackTrace(); + } + Element root = document.getRootElement(); + + for (Iterator iterator = root.elementIterator("action"); iterator.hasNext();) { + Element e = iterator.next(); + String actionName = e.attributeValue("name"); + String clazName = e.attributeValue("class"); + ActionConfig actionConfig = new ActionConfig(actionName,clazName); + for(Iterator childIterator = e.elementIterator();childIterator.hasNext();){ + Element child = childIterator.next(); + String jspKey = child.attributeValue("name"); + String jspValue = child.getTextTrim(); + actionConfig.addViewResult(jspKey,jspValue); + } + actionMap.put(actionName,actionConfig); + } + } + + public String getView(String actionName, String result){ + String jspKey = actionName + "." + result; + return actionMap.get(actionName).getViewName(result); + } + + + public Map getActionMap() { + return actionMap; + } + +} diff --git a/group23/769232552/coding/src/main/java/code02/litestruts/LoginAction.java b/group23/769232552/coding/src/main/java/code02/litestruts/LoginAction.java new file mode 100644 index 0000000000..0799eae71a --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package code02.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/group23/769232552/coding/src/main/java/code02/litestruts/ReflectionUtil.java b/group23/769232552/coding/src/main/java/code02/litestruts/ReflectionUtil.java new file mode 100644 index 0000000000..2a499f104b --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/ReflectionUtil.java @@ -0,0 +1,119 @@ +package code02.litestruts; + +import org.slf4j.LoggerFactory; + +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; + +/** + * Created by yaoyuan on 2017/3/21. + */ +public class ReflectionUtil { + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ReflectionUtil.class); + + private static final Map> clazzMap = new HashMap>(); + + //加载xml文件中的类 + public void initiateClazz(Configuration cfg){ + Map actionMap = cfg.getActionMap(); + + for (Map.Entry entry : actionMap.entrySet()) { + String actionName = entry.getKey(); //login + ActionConfig actionConfig =entry.getValue(); + String className = actionConfig.getClassName(); //code02.litestruts.LoginAction + Class cls; + try { + cls = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); + clazzMap.put(actionName,cls); + } catch (Exception e) { + logger.warn("加载类 " + className + "出错!"); + } + } + } + + + //返回实例对象 + public Object getInstance(String actionName){ + Object instance = null; + for (Map.Entry> entry : clazzMap.entrySet()) { + String action = entry.getKey(); //login + Class cls = entry.getValue(); //code02.litestruts.LoginAction.class + if(actionName.equals(action)){ + try { + instance = cls.newInstance(); + } catch (Exception e) { + logger.error("生成实例出错!", e); + throw new RuntimeException(e); + } + } + } + return instance; + } + + + //参数赋值 + public 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 (InvocationTargetException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + } + + //运行无参方法 + public Object runMethodWithoutParams(Object o , String methodName){ + Class clz = o.getClass(); + Object result = null; + try { + Method method = clz.getDeclaredMethod(methodName); + try { + result = method.invoke(o); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + return result; + } + + //返回以set开头的方法 + public List getSetterMethods(Object o){ + return getMethods(o.getClass(),"set"); + } + + //返回以get开头的方法 + public List getGetterMethods(Object o){ + return getMethods(o.getClass(),"get"); + } + + private List getMethods(Class clz, String startWithName){ + List methodsList = new ArrayList(); + Method[] methods = clz.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + String methodName = methods[i].getName(); + if(methodName.startsWith(startWithName)){ + methodsList.add(methods[i]); + } + } + return methodsList; + } + +} diff --git a/group23/769232552/coding/src/main/java/code02/litestruts/Struts.java b/group23/769232552/coding/src/main/java/code02/litestruts/Struts.java new file mode 100644 index 0000000000..b954f25bd5 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/Struts.java @@ -0,0 +1,76 @@ +package code02.litestruts; + +import org.slf4j.LoggerFactory; + +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 { + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Struts.class); + /* + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + + + + */ + public static View runAction(String actionName, Map parameters) { + View view = new View(); + Configuration cfg = new Configuration("src/main/resources/struts.xml"); + ReflectionUtil reflectionUtil = new ReflectionUtil(); + reflectionUtil.initiateClazz(cfg); + /* 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象)*/ + Object o = reflectionUtil.getInstance(actionName); + /*2. 根据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") ,那就应该调用 setName和setPassword方法*/ + reflectionUtil.setParameters(o,parameters); + /*3. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success"*/ + String result = (String) reflectionUtil.runMethodWithoutParams(o,"execute"); + /* 4. 通过反射找到对象的所有getter方法(例如 getMessage),通过反射来调用, + 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} ,放到View对象的parameters*/ + Map params = new HashMap(); + List methods = reflectionUtil.getGetterMethods(o); + for(Method method : methods){ + String key = method.getName().substring(3); + String value = null; + try { + value = (String) method.invoke(o); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + params.put(key,value); + } + /*5. 根据struts.xml中的 配置,以及execute的返回值,确定哪一个jsp,放到View对象的jsp字段中。*/ + String jsp = cfg.getView(actionName,result); + view.setParameters(params); + view.setJsp(jsp); + + return view; + } + + public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { + + String actionName = "login"; + HashMap params = new HashMap(); + params.put("name","test"); + params.put("password","12345"); + + View view = Struts.runAction(actionName,params); + System.out.println(view.getJsp()); + System.out.println(view.getParameters()); + + + } + +} diff --git a/group23/769232552/coding/src/main/java/code02/litestruts/View.java b/group23/769232552/coding/src/main/java/code02/litestruts/View.java new file mode 100644 index 0000000000..c7e630587c --- /dev/null +++ b/group23/769232552/coding/src/main/java/code02/litestruts/View.java @@ -0,0 +1,23 @@ +package code02.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/group23/769232552/coding/src/main/java/code03/DownloadThread.java b/group23/769232552/coding/src/main/java/code03/DownloadThread.java new file mode 100644 index 0000000000..7bf8a8e765 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/DownloadThread.java @@ -0,0 +1,47 @@ +package code03; + +import code03.api.Connection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; + +/** + * 定义线程类 + */ + + +public class DownloadThread extends Thread{ + + private static final Logger logger = LoggerFactory.getLogger(DownloadThread.class); + + private Connection conn; + private int startPos; + private int endPos; + private static final String fileName = "D://test.png"; + + + public DownloadThread(Connection conn, int startPos, int endPos){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + + @Override + public void run(){ + logger.debug("thread {} begin to download from start {} to end {} ",Thread.currentThread().getName(),startPos,endPos); + + try { + byte[] data = conn.read(startPos,endPos); + RandomAccessFile rfile = new RandomAccessFile(fileName,"rw"); + rfile.seek(startPos); + rfile.write(data,0,data.length); + rfile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + logger.debug("thread {} end to download from start {} to end {} ",Thread.currentThread().getName(),startPos,endPos); + + + } +} diff --git a/group23/769232552/coding/src/main/java/code03/FileDownloader.java b/group23/769232552/coding/src/main/java/code03/FileDownloader.java new file mode 100644 index 0000000000..6814c49f9c --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/FileDownloader.java @@ -0,0 +1,109 @@ +package code03; + +import code03.api.Connection; +import code03.api.ConnectionException; +import code03.api.ConnectionManager; +import code03.api.DownloadListener; +import code03.impl.ConnectionManagerImpl; + +import java.util.ArrayList; +import java.util.List; + +/** + * 线程启动类 + */ + +public class FileDownloader { + + private String url; + private DownloadListener listener; + private ConnectionManager cm; + private static boolean downloadFinished = false; + + private final static int THREAD_NUM = 5; + + public FileDownloader(String _url) { + this.url = _url; + } + + /* + (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。*/ + public void execute(){ + Connection conn = null; + try { + //启动线程 + int startPos = 0, endPos = 0; + List threads = new ArrayList(); + for (int i = 0; i < THREAD_NUM; i++) { + conn = cm.open(this.url); //每次都要重新获取一个connection.imputstream + int length = conn.getContentLength(); + startPos = length/THREAD_NUM * i; + endPos = length/THREAD_NUM * (i + 1)- 1; + DownloadThread downloadThread = new DownloadThread(conn,startPos,endPos); + threads.add(downloadThread); + downloadThread.start(); + } + + //调用join方法,确保所有线程的工作已经完成 + for (int i = 0; i < THREAD_NUM; i++) { + try { + threads.get(i).join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + listener.notifyFinished(); + } 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 static void main(String[] args) { + + String url = "http://litten.me/assets/blogImg/litten.png"; + FileDownloader fileDownloader = new FileDownloader(url); + ConnectionManager cm = new ConnectionManagerImpl(); + fileDownloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + }); + fileDownloader.setConnectionManager(cm); + fileDownloader.execute(); + + + while (!downloadFinished){ + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("download finished ! "); + + + } + +} diff --git a/group23/769232552/coding/src/main/java/code03/api/Connection.java b/group23/769232552/coding/src/main/java/code03/api/Connection.java new file mode 100644 index 0000000000..1f2e4e1d39 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/api/Connection.java @@ -0,0 +1,23 @@ +package code03.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/group23/769232552/coding/src/main/java/code03/api/ConnectionException.java b/group23/769232552/coding/src/main/java/code03/api/ConnectionException.java new file mode 100644 index 0000000000..77e886e987 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/api/ConnectionException.java @@ -0,0 +1,9 @@ +package code03.api; + +public class ConnectionException extends Exception { + + public ConnectionException(String message,Throwable e){ + super(message,e); + } + +} diff --git a/group23/769232552/coding/src/main/java/code03/api/ConnectionManager.java b/group23/769232552/coding/src/main/java/code03/api/ConnectionManager.java new file mode 100644 index 0000000000..4cbd46445a --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package code03.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group23/769232552/coding/src/main/java/code03/api/DownloadListener.java b/group23/769232552/coding/src/main/java/code03/api/DownloadListener.java new file mode 100644 index 0000000000..f5e7e146a7 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/api/DownloadListener.java @@ -0,0 +1,5 @@ +package code03.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group23/769232552/coding/src/main/java/code03/impl/ConnectionImpl.java b/group23/769232552/coding/src/main/java/code03/impl/ConnectionImpl.java new file mode 100644 index 0000000000..069f21625b --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/impl/ConnectionImpl.java @@ -0,0 +1,107 @@ +package code03.impl; + +import code03.api.Connection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLConnection; + + +public class ConnectionImpl implements Connection{ + + private static final Logger logger = LoggerFactory.getLogger(ConnectionImpl.class); + + + private URLConnection urlConnection; + private int length = -1; + + public ConnectionImpl(URLConnection urlConnection){ + this.urlConnection = urlConnection; + } + + /** + * 读取urlConnection.getInputStream()中的数据,返回byte[] + */ + @Override + public byte[] read(int startPos, int endPos) throws IOException { + int contentLength = getContentLength(); + if(startPos < 0 || endPos > contentLength || contentLength <= 0){ + logger.info("index out of range !"); + return null; + } + + InputStream raw = null; + BufferedInputStream in = null; + int size = endPos - startPos + 1; + + byte[] data = new byte[size]; + try{ + raw = urlConnection.getInputStream(); + in = new BufferedInputStream(raw); + in.skip(startPos); + + int offset = 0; + while(offset < size){ + int bytesRead = in.read(data, offset, size - offset); + while (bytesRead == -1){break;} + offset += bytesRead; + } + } catch (IOException e) { + e.printStackTrace(); + }finally { + raw.close(); + in.close(); + } + return data; + } + + @Override + public int getContentLength() { + if(length != -1){ + return length; + } + length = urlConnection.getContentLength(); + + //if without content-length header + if(length == -1) { + int offset = 0; + InputStream raws = null; + BufferedInputStream ins = null; + try { + raws = urlConnection.getInputStream(); + ins = new BufferedInputStream(raws); + + int max_size = 1024 * 1024;//1M + byte[] data = new byte[max_size]; + + int bytesRead = 0; + while (bytesRead != -1) { + ins.read(data, offset, max_size - offset); + offset += bytesRead; + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + raws.close(); + ins.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + length = offset; + } + return length; + } + + @Override + public void close() { + if(urlConnection != null){ + urlConnection = null; + } + } + +} diff --git a/group23/769232552/coding/src/main/java/code03/impl/ConnectionManagerImpl.java b/group23/769232552/coding/src/main/java/code03/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..5078c7608c --- /dev/null +++ b/group23/769232552/coding/src/main/java/code03/impl/ConnectionManagerImpl.java @@ -0,0 +1,36 @@ +package code03.impl; + +import code03.api.Connection; +import code03.api.ConnectionException; +import code03.api.ConnectionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +/** + * 获取Connection实例 + */ + +public class ConnectionManagerImpl implements ConnectionManager { + private static final Logger logger = LoggerFactory.getLogger(ConnectionManagerImpl.class); + + @Override + public Connection open(String url) throws ConnectionException { + Connection connection = null; + try { + URL _url = new URL(url); + URLConnection urlConnection = _url.openConnection(); + connection = new ConnectionImpl(urlConnection); + } catch (MalformedURLException e) { + logger.error("url {} format error",url); + } catch (IOException e) { + e.printStackTrace(); + } + return connection; + } + +} diff --git a/group23/769232552/coding/src/main/resources/struts.xml b/group23/769232552/coding/src/main/resources/struts.xml new file mode 100644 index 0000000000..fd71dc16ff --- /dev/null +++ b/group23/769232552/coding/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/group23/769232552/coding/src/test/java/code01/ArrayListTest.java b/group23/769232552/coding/src/test/java/code01/ArrayListTest.java new file mode 100644 index 0000000000..2bfd7f52e1 --- /dev/null +++ b/group23/769232552/coding/src/test/java/code01/ArrayListTest.java @@ -0,0 +1,67 @@ +package code01; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Created by yaoyuan on 2017/3/8. + */ +public class ArrayListTest { + ArrayList arrayList; + @Before + public void setUp(){ + arrayList = new ArrayList(); + } + + @Test + public void testAdd() throws Exception { + + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + arrayList.add(str); + } + + // size() + Assert.assertEquals(array.length,arrayList.size()); + + //add(),get() + for (int i = 0; i < arrayList.size(); i++){ + Assert.assertEquals(array[i],arrayList.get(i)); + } + } + + @Test + public void testAddWithIndex() throws Exception { + ArrayList arrayList2 = new ArrayList(3);//自动扩容 + String[] array = new String[]{"a","b","c","d","e"}; + for (int i = 0; i < array.length; i++){ + arrayList2.add(i,array[i]); + } + //add(),get() + for (int i = 0; i < arrayList2.size(); i++){ + Assert.assertEquals(array[i],arrayList2.get(i)); + } + arrayList2.add(3,"new"); + Assert.assertEquals("new",arrayList2.get(3)); + + + } + + @Test + public void testRemove() throws Exception { + + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + arrayList.add(str); + } + arrayList.remove(0); + arrayList.remove(0); + + + for (int i = 0; i < arrayList.size(); i++) { + Assert.assertEquals(array[i+2],arrayList.get(i)); + } + + } +} \ No newline at end of file diff --git a/group23/769232552/coding/src/test/java/code01/BinaryTreeTest.java b/group23/769232552/coding/src/test/java/code01/BinaryTreeTest.java new file mode 100644 index 0000000000..8c1f4e8e09 --- /dev/null +++ b/group23/769232552/coding/src/test/java/code01/BinaryTreeTest.java @@ -0,0 +1,27 @@ +package code01; + +import org.junit.Test; + +/** + * Created by yaoyuan on 2017/3/10. + */ +public class BinaryTreeTest { + + @Test + public void testCreateBinaryTree(){ + + BinaryTree binaryTree1 = new BinaryTree(); + BinaryTree binaryTree2 = new BinaryTree(); + Integer[] array1 = new Integer[]{3,4,1,2,5}; + Integer[] array2 = new Integer[]{3,1,4,5,2}; + binaryTree1.createBinaryTree(array1); + binaryTree2.createBinaryTree(array2); + binaryTree1.leftOrderScan(binaryTree1.getRoot()); + binaryTree2.leftOrderScan(binaryTree2.getRoot()); + } + + @Test + public void testInsert(){ + BinaryTree binaryTree3 = new BinaryTree(); + } +} \ No newline at end of file diff --git a/group23/769232552/coding/src/test/java/code01/LinkedListTest.java b/group23/769232552/coding/src/test/java/code01/LinkedListTest.java new file mode 100644 index 0000000000..5481783932 --- /dev/null +++ b/group23/769232552/coding/src/test/java/code01/LinkedListTest.java @@ -0,0 +1,174 @@ +package code01; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Created by yaoyuan on 2017/3/8. + */ +public class LinkedListTest { + + @Test + public void testAdd() throws Exception { + + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + + // size() + Assert.assertEquals(array.length,linklist.size()); + + //add(),get() + for (int i = 0; i < linklist.size(); i++){ + Assert.assertEquals(array[i],linklist.get(i)); + } + + } + + @Test + public void testAddWithIndex() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + + //add(),get() + for (int i = 0; i < linklist.size(); i++){ + Assert.assertEquals(array[i],linklist.get(i)); + } + + String str = "new"; + linklist.add(0,str); + Assert.assertEquals(str,linklist.get(0)); + + linklist.add(3,str); + Assert.assertEquals(str,linklist.get(3)); + + linklist.add(linklist.size() ,str); + Assert.assertEquals(str,linklist.get(linklist.size()-1)); + } + + @Test + public void testRemove() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + + //remove(),get() + Assert.assertEquals(linklist.remove(0),array[0]); + Assert.assertEquals(linklist.size(),array.length - 1); + + Assert.assertEquals(linklist.remove(linklist.size() - 1),array[array.length-1]); + Assert.assertEquals(linklist.size(),array.length - 2); + + } + + @Test + public void testAddFirst() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + //addFirst(),get() + String str = "new"; + linklist.addFirst(str); + Assert.assertEquals(str,linklist.get(0)); + Assert.assertEquals(linklist.size(),array.length + 1); + } + + @Test + public void testAddLast() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + //addLast(),get() + String str = "new"; + linklist.addLast(str); + Assert.assertEquals(str,linklist.get(linklist.size()-1)); + Assert.assertEquals(linklist.size(),array.length + 1); + } + + @Test + public void testRemoveFirst() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + //removeFirst(),get() + Assert.assertEquals(linklist.removeFirst(),array[0]); + Assert.assertEquals(linklist.size(),array.length - 1); + } + + @Test + public void testRemoveLast() throws Exception { + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + //removeLast(),get() + Assert.assertEquals(linklist.removeLast(),array[array.length-1]); + Assert.assertEquals(linklist.size(),array.length - 1); + + } + + @Test + public void testReverse(){ + LinkedList linklist = new LinkedList(); + String[] array = new String[]{"a","b","c","d","e"}; + for (String str : array){ + linklist.add(str); + } + linklist.reverse(); + 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"); //密码和预设的不一致 + + 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/group23/769232552/coding/src/test/java/code03/FileDownloaderTest.java b/group23/769232552/coding/src/test/java/code03/FileDownloaderTest.java new file mode 100644 index 0000000000..cdc58d24b3 --- /dev/null +++ b/group23/769232552/coding/src/test/java/code03/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package code03; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import code03.api.ConnectionManager; +import code03.api.DownloadListener; +import code03.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://litten.me/assets/blogImg/litten.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/liuxin/src/com/coderising/download/.classpath b/group23/810181789/.classpath similarity index 81% rename from liuxin/src/com/coderising/download/.classpath rename to group23/810181789/.classpath index ac37fb2e4b..fb5011632c 100644 --- a/liuxin/src/com/coderising/download/.classpath +++ b/group23/810181789/.classpath @@ -1,5 +1,6 @@ + diff --git a/group23/810181789/.gitignore b/group23/810181789/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group23/810181789/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group23/810181789/.project b/group23/810181789/.project new file mode 100644 index 0000000000..d78dba00af --- /dev/null +++ b/group23/810181789/.project @@ -0,0 +1,17 @@ + + + basicstructure + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group23/810181789/src/firstday/ArrayListt.java b/group23/810181789/src/firstday/ArrayListt.java new file mode 100644 index 0000000000..229c588f33 --- /dev/null +++ b/group23/810181789/src/firstday/ArrayListt.java @@ -0,0 +1,86 @@ +package firstday; + +import java.util.Arrays; + +public class ArrayListt { + private Object arr[]=new Object[10]; + private int pos=0; + public boolean add(Object o) + { + if(pos=arr.length) + { + arr=Arrays.copyOf(arr, arr.length+1); + arr[pos] = o; + pos++; + return true; + } + return false; + } + public boolean add(Object o, int index) + { + if(pos=arr.length) + { + arr=Arrays.copyOf(arr, arr.length+1); + for(int i=arr.length-2;i>=index;i--) + { + arr[i+1] = arr[i]; + } + arr[index] = o; + return true; + } + return false; + } + public Object get(int i) + { + Object o = arr[i]; + return o; + } + public Object remove(int index) + { + Object var=arr[index]; + for(int i=index+1;i + diff --git a/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore new file mode 100644 index 0000000000..2c93a035dc --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore @@ -0,0 +1,27 @@ +*.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.* + +# Idea +*.iml +*.ipr +*.iws +.idea + +target diff --git a/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/ArrayUtil.java b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/ArrayUtil.java new file mode 100644 index 0000000000..149f196397 --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/ArrayUtil.java @@ -0,0 +1,201 @@ +package com.github.xiaozi123.coding2017.secondWork; + +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[] reverseArray=new int[origin.length]; + for (int i = 0; i < reverseArray.length/2; i++) { + reverseArray[i]=origin[origin.length-i-1]; + } + + } + + /** + * µһ飺 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[] newArray=new int[oldArray.length]; + + for (int i = 0,j=0; i < oldArray.length; i++,j++) { + if (oldArray[i]==0) { + i++; + } + newArray[j]=oldArray[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){ + ArrayList list1 = new ArrayList(Arrays.asList(array1)); + ArrayList list2 = new ArrayList(Arrays.asList(array2)); + list1.removeAll(list2); + Integer[] integers=(Integer[]) list1.toArray(); + int[] intArray = new int[integers.length]; + for(int i=0; i < integers.length; i ++) + { + intArray[i] = integers[i].intValue(); + } + return intArray; + } + /** + * һѾݵ 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){ + if (oldArray==null||size>=0) { + throw new IndexOutOfBoundsException("."); + + } + int[] resultArray=new int[oldArray.length+size]; + System.arraycopy(oldArray, 0, resultArray, 0,oldArray.length); + return resultArray; + } + + /** + * 쳲Ϊ1123581321...... һֵ Сڸֵ + * 磬 max = 15 , 򷵻صӦΪ [11235813] + * max = 1, 򷵻ؿ [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + int[] array=new int[max]; + for (int i = 0; i < max; i++) { + array[i]=getFibo(i);//i + if (array[i]>=max) { + break; + } + } + return array; + } + + // ȡi + private static int getFibo(int i) { + if (i == 1 || i == 2) + return 1; + else + return getFibo(i - 1) + getFibo(i - 2);} + + + + /** + * Сڸֵmax + * max = 23, صΪ[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + int[] array=new int[max]; + for (int i = 0,j=0; i < max; i++) { + if (isPrime(i)) { + array[j]=i; + j++; + } + + } + return array; + } + public static boolean isPrime(int a) { + boolean flag = true; + + if (a < 2) {// С2 + return false; + } else { + + for (int i = 2; i <= Math.sqrt(a); i++) { + + if (a % i == 0) {// ܱ˵false + + flag = false; + break;// ѭ + } + } + } + return flag; + } + + /** + * ν ָǡõ֮ͣ6=1+2+3 + * һֵmax һ飬 Сmax + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + int[] array=new int[max]; + for (int i = 0,j=0; i < max; i++) { + if (isPrime(i)) { + array[j]=i; + j++; + } + + } + return array; + } + + public static boolean isPerfectNumber(int i) { + int s=0; + for(int j=1;j0&&array!=null) { + StringBuffer stringBuffer=new StringBuffer(); + stringBuffer.append(array[0]); + for (int i = 1; i < array.length; i++) { + stringBuffer.append(seperator).append(array[i]); + } + return stringBuffer.toString(); + } + return null; + } + + +} diff --git a/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/LoginAction.java b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/LoginAction.java new file mode 100644 index 0000000000..6c8e4026ce --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/LoginAction.java @@ -0,0 +1,41 @@ +package com.github.xiaozi123.coding2017.secondWork; + + +/** + * һչʾ¼ҵ࣬ еû붼Ӳġ + * @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/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/Struts.java b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/Struts.java new file mode 100644 index 0000000000..2f267a2491 --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/Struts.java @@ -0,0 +1,145 @@ +package com.github.xiaozi123.coding2017.secondWork; + +import java.util.Map; + +import java.io.File; +import java.io.InputStream; +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; + +import com.sun.corba.se.impl.oa.poa.ActiveObjectMap.Key; + + + +public class Struts { + + + + public static View runAction(String actionName, Map parameters) throws DocumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + + /* + + 0. ȡļstruts.xml + + 1. actionNameҵӦclass LoginAction, ͨʵ + parametersеݣösetter parametersе + ("name"="test" , "password"="1234") , + ǾӦõ setNamesetPassword + + 2. ͨöexectue ÷ֵ"success" + + 3. ͨҵgetter getMessage, + ͨã ֵγһHashMap , {"message": "¼ɹ"} , + ŵViewparameters + + 4. struts.xmlе ,Լexecuteķֵ ȷһjsp + ŵViewjspֶС + + */ + //ȡxmlļ + +// String path="src/com/github/xiaozi123.coding2017.secondWork/struct.xml"; + + + + return initView(actionName, parameters); + } + + public static View initView(String actionName, Map parameters) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + View view=new View(); + int i=0; + String[] methodNames=new String[parameters.size()]; + + for (String string : parameters.keySet()) { + methodNames[i++]="set" + +string.substring(0, 1).toUpperCase()+string.substring(1); + } + + Struts.class.getResourceAsStream("/structs.xml"); + Element element=getTargetElement(actionName); + + //ͨʵ + String className=element.attribute(1).getValue(); + Class clazz=Class.forName(className); + + Object object=clazz.newInstance(); + + invokeObjectSetter(parameters, methodNames, clazz, object); + + view.setParameters(createGetterMap(clazz, object)); + setViewJsp(view, element, clazz, object); + return view; + + } + + + private static void setViewJsp(View view, Element element, Class clz, Object obj) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + view.setJsp(getJsp(element, executeToGetResult(clz, obj))); + } + + + private static Map createGetterMap(Class clz, Object obj) throws IllegalAccessException, 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(); + Object value = item.invoke(obj); + map.put(key, value); + } + } + return map; + } + + private static String executeToGetResult(Class clz, Object obj) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + // ȡ ִ + Method method = clz.getMethod("execute"); + String result = (String) method.invoke(obj); + return result; + } + + private static void invokeObjectSetter(Map parameters, + String[] methodNames, Class clz, Object obj) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + for (String key : methodNames) { + Method method = clz.getMethod(key, String.class); + method.invoke(obj, parameters.get(key)); + } + } + + private static Element getTargetElement(String actionName) throws DocumentException { + SAXReader reader = new SAXReader(); + InputStream inputStream =Struts.class.getResourceAsStream("/struts.xml"); + Document document = reader.read(inputStream); + Element rootNode = document.getRootElement(); + List elements = rootNode.elements(); + for (Element item : elements) { + if (actionName.equals(item.attribute(0).getValue())) { + return item; + } + } + return null; + } + + private static String getJsp(Element element, String result) { + List elements = element.elements(); + for (Element e : elements) { + if (result.equals(e.attribute(0).getValue())) { + return e.getTextTrim(); + } + } + return null; + } + +} diff --git a/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/StrutsTest.java b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/StrutsTest.java new file mode 100644 index 0000000000..7e61cb97d9 --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/StrutsTest.java @@ -0,0 +1,46 @@ +package com.github.xiaozi123.coding2017.secondWork; + +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, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, DocumentException { + + 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 ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, DocumentException { + 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/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/View.java b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/View.java new file mode 100644 index 0000000000..5d13e67df3 --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/View.java @@ -0,0 +1,23 @@ +package com.github.xiaozi123.coding2017.secondWork; + +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/group11/1178243325/DataStructure/struts.xml b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/struts.xml similarity index 100% rename from group11/1178243325/DataStructure/struts.xml rename to group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/struts.xml diff --git "a/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/\346\226\207\347\253\240\345\234\260\345\235\200.txt" "b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/\346\226\207\347\253\240\345\234\260\345\235\200.txt" new file mode 100644 index 0000000000..4aa14355dc --- /dev/null +++ "b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/\346\226\207\347\253\240\345\234\260\345\235\200.txt" @@ -0,0 +1,2 @@ +飺http://www.jianshu.com/p/8a15d1c12bc0 +CSDNhttp://blog.csdn.net/qq_23038639/article/details/63252328 \ No newline at end of file diff --git a/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0312/basic/ArrayList.java b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0312/basic/ArrayList.java index c93b6c76e0..6fde63911f 100644 --- a/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0312/basic/ArrayList.java +++ b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0312/basic/ArrayList.java @@ -12,13 +12,14 @@ public class ArrayList implements List { public void add(Object o) { - if (elementData.length < size + 1) { - Object[] target = new Object[size + 1]; - System.arraycopy(elementData, 0, target, 0, elementData.length); - elementData = target; - } - elementData[size] = o; - size = size + 1; +// if (elementData.length < size + 1) { +// Object[] target = new Object[size + 1]; +// System.arraycopy(elementData, 0, target, 0, elementData.length); +// elementData = target; +// } +// elementData[size] = o; +// size = size + 1; + add(size, o); } @@ -29,7 +30,7 @@ public void add(int index, Object o) throws IndexOutOfBoundsException { int leftSize = index; int rightSize = size - index; - Object[] target = new Object[elementData.length + 1]; + Object[] target = new Object[size + 1]; System.arraycopy(elementData, 0, target, 0, leftSize); target[index] = o; System.arraycopy(elementData, index, target, index + 1, rightSize); diff --git a/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/array/ArrayUtil.java b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/array/ArrayUtil.java new file mode 100644 index 0000000000..94f7b60c64 --- /dev/null +++ b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/array/ArrayUtil.java @@ -0,0 +1,337 @@ +package me.lzb.homework0319.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[] target = new int[origin.length]; + for (int i = 0; i < origin.length; i++) { + target[i] = origin[origin.length - 1 - i]; + } + origin = target; + } + + /** + * 现在有如下的一个数组: 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 l = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + l = l + 1; + } + } + + int[] target = new int[l]; + + int a = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + target[a] = oldArray[i]; + a = a + 1; + } + } + + return target; + } + + /** + * 给定两个已经排序好的整形数组, 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[] tmp = new int[array1.length + array2.length]; + + + int mini = 0; + int a1 = array1[0]; + int a2 = array2[0]; + + if(a1 < a2){ + mini = a1; + }else { + mini = a2; + } + + tmp[0] = mini; + + int l3 = 0; + + for (int i = 1; i < array1.length + array2.length; i++) { + +// if(mini >= array1[l1 - 1] && mini >= array2[l2 - 1]){ +// l3 = i; +// break; +// } + + int oldMin = mini; + + + + int aa1 = mini; + if(mini < array1[array1.length - 1] ){ + for (int j = 0; j < array1.length; j++) { + if(array1[j] > mini){ + aa1 = array1[j]; + break; + } + } + + } + + int aa2 = mini; + if(mini < array2[array2.length - 1] ){ + for (int j = 0; j < array2.length; j++) { + if(array2[j] > mini){ + aa2 = array2[j]; + break; + } + } + } + + + if(aa1 != oldMin && aa2 != oldMin){ + if(aa1 < aa2){ + mini = aa1; + }else { + mini = aa2; + } + }else if(aa1 != oldMin){ + mini = aa1; + }else { + mini = aa2; + } + + + if(oldMin == mini){ + l3 = i; + break; + } + + tmp[i] = mini; + } + + int[] result = new int[l3]; + + System.arraycopy(tmp, 0, result, 0, l3); + + + + 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) { + 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) { + if (max <= 1){ + return new int[0]; + } + + int[] result = {1, 1}; + + + int i = 2; + + int n = 0; + + while (n < max){ + int[] t = new int[result.length + 1]; + System.arraycopy(result, 0, t, 0, result.length); + n = t[i-1] + t[i - 2]; + + if(n >= max){ + return result; + } + + t[i] = n; + + result = t; + i = i + 1; + } + + return null; + } + + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + if (max <= 2){ + return new int[0]; + } + + if (max == 3){ + return new int[]{2}; + } + + + int[] primes = new int[max+1]; + primes[0] = 2; + int count = 1; + for (int i = 3; i < max; i = i + 2) { + + boolean isPrime = true; + for (int j = 3; j < i; j++) { + if(i % j == 0){ + isPrime = false; + break; + } + } + + if(isPrime){ + primes[count] = i; + count = count + 1; + } + } + + int[] result = new int[count]; + System.arraycopy(primes, 0, result, 0, count); + + return result; + + } + + private boolean isPrime(int a){ + if (a < 2) { + return false; + } + + if (a == 2) { + return true; + } + + if(a % 2 == 0){ + return false; + } + + + for (int i = 3; i < a; i = i + 2) { + if(a % i == 0){ + return false; + } + } + + return true; + } + + + + /** + * 所谓“完数”, 是指这个数恰好等于它的真因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + if (max < 6){ + return new int[0]; + } + + + int[] pns = new int[max]; + + int count = 0; + for (int i = 6; i < max; i++) { + if (isPerfectNumber(i)){ + pns[count] = i; + count = count + 1; + } + } + + + + int[] result = new int[count]; + System.arraycopy(pns, 0, result, 0, count); + return result; + } + + + private boolean isPerfectNumber(int a){ + if(a < 6){ + return false; + } + + int sum = 0; + for (int i = 1; i < a; i++) { + if(a % i == 0){ + sum = sum + i; + } + } + + return sum == a; + } + + + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @return + */ + public static String join(int[] array, String seperator) { + String result = ""; + for (int i = 0; i < array.length; i++) { + result = result + array[i] + seperator ; + } + + result = result.substring(0, result.length() - 1); + return result; + } + +} diff --git a/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/LoginAction.java b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/LoginAction.java new file mode 100644 index 0000000000..4c4ca22187 --- /dev/null +++ b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package me.lzb.homework0319.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/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/Struts.java b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/Struts.java new file mode 100644 index 0000000000..aea8d1105d --- /dev/null +++ b/group24/1148285693/learning2017/learning-basic/src/main/java/me/lzb/homework0319/litestruts/Struts.java @@ -0,0 +1,113 @@ +package me.lzb.homework0319.litestruts; + +import org.apache.commons.lang3.StringUtils; +import org.dom4j.DocumentException; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + + +/* + +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字段中。 + +*/ + + +public class Struts { + + private static final String XML = "struts.xml"; + + private static final XmlUtil resource = createResource(XML); + + private static XmlUtil createResource(String xml){ + try { + return new XmlUtil(xml); + } catch (DocumentException e) { + e.printStackTrace(); + } + return null; + } + + + public static View runAction(String actionName, Map parameters) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { + + Object loginAction = getAuctionByName(actionName); + + invokeSetMethods(loginAction, parameters); + + String resultName = invokeExecute(loginAction).toString(); + + View view = new View(); + view.setJsp(resource.getResultJsp(actionName, resultName)); + view.setParameters(invokeGetMethods(loginAction)); + + return view; + } + + private static Object getAuctionByName(String auctionName) throws ClassNotFoundException, IllegalAccessException, InstantiationException { + Class c = Class.forName(resource.getAuctionPathByName(auctionName)); + return c.newInstance(); + } + + + private static Object invokeExecute(Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Class c = o.getClass(); + Method mExectue = c.getDeclaredMethod("execute"); + return mExectue.invoke(o); + } + + + private static void invokeSetMethods(Object o, Map parameteMap) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Class c = o.getClass(); + Method[] methods = c.getDeclaredMethods(); + for (int i = 0; i< methods.length; i++) { + String name = methods[i].getName(); + if(StringUtils.startsWith(name, "set")){ + String key = name.replaceAll("^set", "").toLowerCase(); + if(parameteMap.containsKey(key)){ + methods[i].invoke(o, parameteMap.get(key)); + } + } + } + +// //这样参数类型不固定的话不好搞 +// for (Map.Entry entry : parameteMap.entrySet()) { +// Method mSetter = c.getDeclaredMethod("set" + StringUtils.capitalize(entry.getKey()), String.class); +// mSetter.invoke(o, entry.getValue()); +// } + } + + + private static Map invokeGetMethods(Object o) throws InvocationTargetException, IllegalAccessException { + Map resultMap = new HashMap(); + Class c = o.getClass(); + Method[] methods = c.getDeclaredMethods(); + for(int i =0 ;i + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/ArrayListTest.java b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/ArrayListTest.java index c35ed8d2b4..4938e6a8ac 100644 --- a/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/ArrayListTest.java +++ b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/ArrayListTest.java @@ -1,5 +1,7 @@ package me.lzb.homework0312.basic; +import me.lzb.homework0312.basic.ArrayList; +import me.lzb.homework0312.basic.Iterator; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -68,29 +70,21 @@ public void addTest() { @Test public void removeTest() throws IndexOutOfBoundsException { - - ArrayList list = new ArrayList(); - list.add("a"); - list.add("b"); - list.add("c"); - list.add("d"); - - - String r1 = list.remove(1).toString(); + String r1 = arrayList.remove(1).toString(); Assert.assertEquals("b", r1); - Assert.assertEquals(3, list.size()); + Assert.assertEquals(3, arrayList.size()); - String r0 = list.remove(0).toString(); + String r0 = arrayList.remove(0).toString(); Assert.assertEquals("a", r0); - Assert.assertEquals(2, list.size()); + Assert.assertEquals(2, arrayList.size()); - String rs = list.remove(list.size() - 1).toString(); + String rs = arrayList.remove(arrayList.size() - 1).toString(); Assert.assertEquals("d", rs); - Assert.assertEquals(1, list.size()); + Assert.assertEquals(1, arrayList.size()); thrown.expect(IndexOutOfBoundsException.class); thrown.expectMessage("index boom"); - list.remove(100); + arrayList.remove(100); } diff --git a/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/LinkedListTest.java b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/LinkedListTest.java index 740d8768c7..0d48c290f1 100644 --- a/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/LinkedListTest.java +++ b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0312/basic/LinkedListTest.java @@ -1,5 +1,7 @@ package me.lzb.homework0312.basic; +import me.lzb.homework0312.basic.Iterator; +import me.lzb.homework0312.basic.LinkedList; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -69,30 +71,22 @@ public void addTest() { @Test public void removeTest() throws IndexOutOfBoundsException { - - LinkedList list = new LinkedList(); - list.add("a"); - list.add("b"); - list.add("c"); - list.add("d"); - - - String r1 = list.remove(1).toString(); + String r1 = linkedList.remove(1).toString(); Assert.assertEquals("b", r1); - Assert.assertEquals(3, list.size()); + Assert.assertEquals(3, linkedList.size()); - String r0 = list.remove(0).toString(); + String r0 = linkedList.remove(0).toString(); Assert.assertEquals("a", r0); - Assert.assertEquals(2, list.size()); + Assert.assertEquals(2, linkedList.size()); - String rs = list.remove(list.size() - 1).toString(); + String rs = linkedList.remove(linkedList.size() - 1).toString(); Assert.assertEquals("d", rs); - Assert.assertEquals(1, list.size()); + Assert.assertEquals(1, linkedList.size()); thrown.expect(IndexOutOfBoundsException.class); thrown.expectMessage("index boom"); - list.remove(100); - list.remove(-1); + linkedList.remove(100); + linkedList.remove(-1); } diff --git a/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0319/litestruts/StrutsTest.java b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0319/litestruts/StrutsTest.java new file mode 100644 index 0000000000..027c33eba9 --- /dev/null +++ b/group24/1148285693/learning2017/learning-basic/src/test/java/me/lzb/homework0319/litestruts/StrutsTest.java @@ -0,0 +1,41 @@ +package me.lzb.homework0319.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + + + +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/group24/1148285693/learning2017/learning-basic/src/test/resources/litestruts/struts.xml b/group24/1148285693/learning2017/learning-basic/src/test/resources/litestruts/struts.xml new file mode 100644 index 0000000000..81c153757c --- /dev/null +++ b/group24/1148285693/learning2017/learning-basic/src/test/resources/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/1148285693/learning2017/pom.xml b/group24/1148285693/learning2017/pom.xml index 6493774794..4951c1ff42 100644 --- a/group24/1148285693/learning2017/pom.xml +++ b/group24/1148285693/learning2017/pom.xml @@ -65,13 +65,43 @@ - + junit junit 4.12 + + + dom4j + dom4j + 1.6.1 + + + + jaxen + jaxen + 1.1.6 + + + + + commons-io + commons-io + 2.5 + + + org.apache.commons + commons-lang3 + 3.5 + + + commons-codec + commons-codec + 1.10 + + diff --git a/group24/120509419/ArrayList.java b/group24/120509419/ArrayList.java new file mode 100644 index 0000000000..cbb7084045 --- /dev/null +++ b/group24/120509419/ArrayList.java @@ -0,0 +1,123 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +import java.util.Arrays; + +/** + * + * @author CJ + */ +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + private final int defaultGrowSize = 100; // 每次增长 100 个元素 + +// private int curIterIndex = 0; // 用于记录 Iterator的索引 + + private void CheckAndGrowUp() { + if (size+1 > elementData.length) { + elementData = Arrays.copyOf(elementData, elementData.length + defaultGrowSize); + } + } + + // 添加一个方法,检测看,添加元素的话,是否需要增长,专门用于数组长度扩展的 + public void add(Object o) { + CheckAndGrowUp(); + elementData[size] = o; + size++; + } + + @Override + public void add(int index, Object o) { + // 先探测是否添加数组大小 + CheckAndGrowUp(); + // 保留后半部分,然后 全部替换即可 + + Object[] tmpObjectArr = Arrays.copyOfRange(elementData, index, elementData.length); + elementData[index] = o; + for (int i = index+1; i < size+1; i++) { + elementData[i] = tmpObjectArr[i-index-1]; + } + size++; + + } + + public Object get(int index) { + // 应该是 不需要跑出 下标越界异常的,因为数组越界会自动抛出 + return elementData[index]; + } + + public Object remove(int index) { + for (int i = index; i < size; i++) { + elementData[i] = elementData[i + 1]; + } + elementData[size] = null; // 后续后面是 数值?那么就不能为null了,而是零? + size--; + return null; + } + + @Override + public int size() { + return size; + } + + // 覆盖toString方法,方便测试 + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("ArrayList: ["); + for (int i = 0; i < size; i++) { + sb.append(elementData[i]).append(", "); + } +// System.err.println(size); + sb.delete(sb.length()-2,sb.length()).append("]"); + return sb.toString(); + } + + public Iterator iterator() { + + return new Iterator() { + int curIterIndex = 0; + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return curIterIndex < size; + } + + @Override + public Object next() { + // TODO Auto-generated method stub + return elementData[curIterIndex++]; + } + + }; + } + + public static void main(String[] args) { + ArrayList curArrList = new ArrayList(); + for (int i = 0; i <= 101; i++) { + curArrList.add(i); + } + System.err.println("Test add Arr"); + System.err.println(curArrList); + System.err.println("Test add in specific index"); + curArrList.add(10, 1010); + System.err.println(curArrList); + System.err.println("Test remove"); + curArrList.remove(10); + System.err.println(curArrList); + System.err.println("Test Iterator"); + Iterator curIter = curArrList.iterator(); + while(curIter.hasNext()){ + System.err.println(curIter.next()); + } + } + +} diff --git a/group24/120509419/BinaryTreeNode.java b/group24/120509419/BinaryTreeNode.java new file mode 100644 index 0000000000..ff40538e64 --- /dev/null +++ b/group24/120509419/BinaryTreeNode.java @@ -0,0 +1,87 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +/** + * + * @author CJ + */ +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) { + // 应该只需要实现这个就可以了 + int curValue = (Integer) this.getData(); + int insertValue = (Integer) o; + + BinaryTreeNode newNode = new BinaryTreeNode(); + newNode.setData(o); + + if (curValue > insertValue) { + if (this.getLeft() != null) { + return this.getLeft().insert(o); + } else { + this.setLeft(newNode); + return this; + } + } else{ + if (this.getRight() != null) { + return this.getRight().insert(o); + } else { + this.setRight(newNode); + return this; + } + } + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(this.getData()).append("\n"); + sb.append(this.getLeft()).append("<--").append(this.getData()).append("\n"); + sb.append(this.getData()).append("-->").append(this.getRight()).append("\n"); + return sb.toString(); + } + + public static void main(String[] args) { + BinaryTreeNode btn = new BinaryTreeNode(); + btn.setData(5); +// btn.insert(5); + btn.insert(7); + btn.insert(8); + btn.insert(9); + btn.insert(4); + + System.err.println(btn); + } + +} diff --git a/group24/120509419/Iterator.java b/group24/120509419/Iterator.java new file mode 100644 index 0000000000..29ab5ecaf0 --- /dev/null +++ b/group24/120509419/Iterator.java @@ -0,0 +1,16 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +/** + * + * @author CJ + */ +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} \ No newline at end of file diff --git a/group24/120509419/JUnitTest/ArrayUtilTest.java b/group24/120509419/JUnitTest/ArrayUtilTest.java new file mode 100644 index 0000000000..bef91785bc --- /dev/null +++ b/group24/120509419/JUnitTest/ArrayUtilTest.java @@ -0,0 +1,164 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author CJ + */ +public class ArrayUtilTest { + + public ArrayUtilTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of reverseArray method, of class ArrayUtil. + */ + @Test + public void testReverseArray() { + System.out.println("reverseArray"); + int[] origin = new int[]{1,2,3,4,5}; + int[] expecteds = new int[]{5,4,3,2,1}; + ArrayUtil instance = new ArrayUtil(); + instance.reverseArray(origin); + Assert.assertArrayEquals(expecteds, origin); + // TODO review the generated test code and remove the default call to fail. + //fail("The test case is a prototype."); + } + + /** + * Test of removeZero method, of class ArrayUtil. + */ + @Test + public void testRemoveZero() { + System.out.println("removeZero"); + int[] oldArray = new int[]{1,2,3,4,5,6,0,0,0,0}; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{1,2,3,4,5,6}; + int[] result = instance.removeZero(oldArray); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of merge method, of class ArrayUtil. + */ + @Test + public void testMerge() { + System.out.println("merge"); + int[] array1 = new int[]{3, 5, 7,8}; + int[] array2 = new int[]{4, 5, 6,7}; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{3,4,5,6,7,8}; + int[] result = instance.merge(array1, array2); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of grow method, of class ArrayUtil. + */ + @Test + public void testGrow() { + System.out.println("grow"); + int[] oldArray = new int[]{1,2,3,4,5}; + int size = 5; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{1,2,3,4,5,0,0,0,0,0}; + int[] result = instance.grow(oldArray, size); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of fibonacci method, of class ArrayUtil. + */ + @Test + public void testFibonacci() { + System.out.println("fibonacci"); + int max = 15; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{1,1,2,3,5,8,13}; + int[] result = instance.fibonacci(max); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of getPrimes method, of class ArrayUtil. + */ + @Test + public void testGetPrimes() { + System.out.println("getPrimes"); + int max = 23; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{2,3,5,7,11,13,17,19}; + int[] result = instance.getPrimes(max); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of getPerfectNumbers method, of class ArrayUtil. + */ + @Test + public void testGetPerfectNumbers() { + System.out.println("getPerfectNumbers"); + int max = 10; + ArrayUtil instance = new ArrayUtil(); + int[] expResult = new int[]{6}; + int[] result = instance.getPerfectNumbers(max); + assertArrayEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + + /** + * Test of join method, of class ArrayUtil. + */ + @Test + public void testJoin() { + System.out.println("join"); + int[] array = new int[]{1,2,3,4,5}; + String seperator = ""; + ArrayUtil instance = new ArrayUtil(); + String expResult = "1-2-3-4-5"; + String result = instance.join(array, seperator); + assertEquals(expResult, result); + // TODO review the generated test code and remove the default call to fail. + // fail("The test case is a prototype."); + } + +} diff --git a/group24/120509419/JUnitTest/struts/StrutsTest.java b/group24/120509419/JUnitTest/struts/StrutsTest.java new file mode 100644 index 0000000000..ebeafa858f --- /dev/null +++ b/group24/120509419/JUnitTest/struts/StrutsTest.java @@ -0,0 +1,46 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass.struts; + +import java.io.FileNotFoundException; +import java.io.IOException; +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 IOException, FileNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { + + 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 IOException, FileNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { + 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/group24/120509419/LinkedList.java b/group24/120509419/LinkedList.java new file mode 100644 index 0000000000..0364c16480 --- /dev/null +++ b/group24/120509419/LinkedList.java @@ -0,0 +1,423 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +import java.util.Arrays; + +/** + * + * @author CJ + */ +public class LinkedList implements List { + + private Node head; + + private int size; +// private int curIterIndex; + + public LinkedList() { + head = new Node(); + size = 0; +// curIterIndex = 0; + } + + public void add(Object o) { + addLast(o); + } + + private Node getNode(int index) { + if (index == -1) { + return head; + } else { + Node returnNode = head.next; + for (int i = 0; i < index; i++) { + returnNode = returnNode.next; + } + return returnNode; + } + } + + public void add(int index, Object o) { + Node preNode = getNode(index - 1); + Node addNode = new Node(); + addNode.data = o; + addNode.next = preNode.next; + preNode.next = addNode; + size++; + } + + public Object get(int index) { + return getNode(index).data; + } + + public Object remove(int index) { + Node preNode = getNode(index - 1); + Node delNode = preNode.next; + preNode.next = delNode.next; + // 返回被删除的Node... 可能是为了测试吧 + size--; + return delNode; + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + Node fNode = new Node(); + fNode.data = o; + fNode.next = head.next; + head.next = fNode; + size++; + } + + public void addLast(Object o) { +// System.err.println("Curr add: "+ o); + Node lastNode = getNode(size - 1); +// System.err.println(lastNode); + Node lNode = new Node(); + lNode.data = o; + lastNode.next = lNode; + size++; + } + + public Object removeFirst() { + return removeFirstNode().data; + } + + private Node removeFirstNode() { + Node firstNode = head.next; + head.next = firstNode.next; + size--; + return firstNode; + } + + public Object removeLast() { + return removeLastNode().data; + } + + private Node removeLastNode() { + Node last2Node = getNode(size - 2); + Node lastNode = last2Node.next; + last2Node.next = null; + size--; + return lastNode; + } + + public Iterator iterator() { + return new Iterator() { +// int curIterIndex = 0; + Node curNode = head; + + @Override + public boolean hasNext() { + return curNode.next != null; + } + + @Override + public Object next() { + curNode = curNode.next; + return curNode.data; + } + }; + } + + private static class Node { + + Object data; + Node next; + } + + /** + * 把该链表逆置 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + + int oriSize = size; + Node newHead = new Node(); + newHead.next = this.removeLastNode(); + Node preNode = newHead.next; + + while (size > 0) { + preNode.next = this.removeLastNode(); + preNode = preNode.next; + } + // 不考虑线程安全的情况下,恢复size + size = oriSize; + head = newHead; + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + */ + public void removeFirstHalf() { + int reDirIndex = size / 2; // java会自动 取 0 + size = size - reDirIndex; + System.err.println(reDirIndex); + Node jumpNode = getNode(reDirIndex); + head.next = jumpNode; + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + Node fromNode = getNode(i - 1); + for (int j = 0; j < length; j++) { + fromNode.next = fromNode.next.next; + size--; + } + } + + /** + * 假定当前链表和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) { + // 这个似乎 不应该是 静态方法 + public int[] getElements(LinkedList list) { + int[] returnIndex = new int[list.size]; + int validCounts = 0; +// Iterator curIter = list.iterator(); +// int curIndex = 0; +// while(curIter.hasNext()){ +// returnIndex[curIndex++] =(Integer) this.get((Integer) curIter.next()); +// } + + // 已知是内外都是玩去排序好的,所以是需要一个高效的算法 + Iterator innerIter = this.iterator(); + Iterator curIter = list.iterator(); + int curCount = 0; + int curIndex; + int preIndex = 0; + + while (curIter.hasNext()) { + curIndex = (Integer) curIter.next(); + if (curIndex < preIndex) { + System.err.println("Warning: Skip index no in sorted order..."); + continue; + } +// int skipCounts = curIndex-preIndex; + for (int i = preIndex; i < curIndex; i++) { + innerIter.next(); + } + validCounts++; + returnIndex[curCount++] = (Integer) innerIter.next(); + preIndex = curIndex + 1; + } + return Arrays.copyOf(returnIndex, validCounts); + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 从当前链表中中删除在list中出现的元素 + * + * @param list + */ + public void subtract(LinkedList list) { + // 假定 当前 链表 和 待删除 链表 都是顺序排序的 + Node preNode = head; + Node curNode; + Iterator element2rmIter = list.iterator(); + while (element2rmIter.hasNext()) { + int curValue2rm = (Integer) element2rmIter.next(); + while (preNode.next != null) { + curNode = preNode.next; + if ((Integer) curNode.data == curValue2rm) { + // 删除 + preNode.next = curNode.next; + }else if((Integer) curNode.data > curValue2rm){ + break; // 跳出内层循环,从而获取下一个待删除数据 + }else { + // 更新 + preNode = curNode; + } + } + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + Node preNode = head; + Node curNode; + while (preNode.next != null) { + curNode = preNode.next; + if (curNode.data == preNode.data) { + preNode.next = curNode.next; + } else { + preNode = curNode; + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + // 假定 当前链表 是 从小到大 排列的 + Node preNode = head; + Node curNode; + while (preNode.next != null) { + curNode = preNode.next; + if (min < (Integer) curNode.data && max > (Integer) curNode.data) { + preNode.next = curNode.next; + } else { + preNode = curNode; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) { + + + LinkedList newList = new LinkedList(); + + // 假定 当前 链表 和 待删除 链表 都是顺序排序的 + Node preNode = head; + Node curNode; + Iterator element2rmIter = list.iterator(); + while (element2rmIter.hasNext()) { + int curValue2rm = (Integer) element2rmIter.next(); + while (preNode.next != null) { + curNode = preNode.next; + if ((Integer) curNode.data == curValue2rm) { + // 删除 + preNode = curNode; + newList.add(curNode.data); // 添加data + }else if((Integer) curNode.data > curValue2rm){ + break; // 跳出内层循环,从而获取下一个待删除数据 + }else { + // 更新 + preNode = curNode; + } + } + } + + + return newList; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("LinkdedList ["); + Node curNode = head; + while (curNode.next != null) { + curNode = curNode.next; + sb.append(curNode.data).append(", "); + } + sb.delete(sb.length() - 2, sb.length()).append("]"); + return sb.toString(); + } + + public void clear() { + head.next = null; + size = 0; + } + + public static void main(String[] args) { + // 先写一些测试 + LinkedList ll = new LinkedList(); + System.err.println("Test Add"); + for (int i = 0; i < 10; i++) { + ll.add(i); + } + System.err.println("Size: " + ll.size); + System.err.println(ll); + System.err.println("Test Add last"); + ll.addLast(10); + System.err.println(ll); + System.err.println("Test Add First"); + ll.addFirst(-1); + System.err.println(ll); + System.err.println("Test remove "); + ll.remove(0); + System.err.println(ll); +// ll.remove(11); +// System.err.println(ll); + ll.removeFirst(); + System.err.println(ll); + ll.removeLast(); + System.err.println(ll); + System.err.println("Test reverse()"); + ll.reverse(); + System.err.println(ll); + System.err.println("Test removeFirstHalf()"); + ll.removeFirstHalf(); + System.err.println(ll); +// System.err.println(9/2); + System.err.println("Test remove()"); + ll.remove(1, 2); + System.err.println(ll); +// System.err.println(ll.); + LinkedList newList = new LinkedList(); + newList.add(3); + newList.add(4); + newList.add(6); + newList.add(5); +// System.err.println(); + ll.clear(); + System.err.println("Re Init"); + for (int i = 0; i < 10; i++) { + ll.add(i); + } + System.err.println(ll); + for (int curI : ll.getElements(newList)) { + System.err.println(curI); + } + ll.clear(); + for (int i = 0; i < 10; i++) { + ll.add(i); + ll.add(i); + ll.add(i); + } + System.err.println(ll); + ll.removeDuplicateValues(); + System.err.println(ll); + System.err.println("Test Remove removeRange(3, 6)"); + ll.removeRange(3, 6); + System.err.println(ll); + + LinkedList rmList = new LinkedList(); + rmList.add(3); + rmList.add(4); + rmList.add(7); + rmList.add(8); + ll.subtract(rmList); + System.err.println("Test subtract(3,4,7,8)"); + System.err.println(ll); + ll.clear(); + for (int i = 0; i < 10; i++) { + ll.add(i); + } + rmList.add(11); + System.err.println(ll); + System.err.println(rmList); + System.err.println(ll.intersection(rmList)); +// System.err.println("Test substract"); +// ll.subtract(newList); +// System.err.println(ll); + + } + +} diff --git a/group24/120509419/List.java b/group24/120509419/List.java new file mode 100644 index 0000000000..d347e59c47 --- /dev/null +++ b/group24/120509419/List.java @@ -0,0 +1,18 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +/** + * + * @author CJ + */ +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/group24/120509419/Queue.java b/group24/120509419/Queue.java new file mode 100644 index 0000000000..4cbc45e065 --- /dev/null +++ b/group24/120509419/Queue.java @@ -0,0 +1,58 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +/** + * + * @author CJ + */ +public class Queue { + + private final LinkedList innerList; + + public Queue(){ + innerList = new LinkedList(); + } + + public void enQueue(Object o) { + innerList.addLast(o); + } + + public Object deQueue() { + return innerList.removeFirst(); + } + + public boolean isEmpty() { + return innerList.size()==0; + } + + public int size() { + return innerList.size(); + } + + public String toString(){ + StringBuilder sb = new StringBuilder(); + sb.append("ArrayList: ["); + for (int i = 0; i < innerList.size(); i++) { + sb.append(innerList.get(i)).append(", "); + } +// System.err.println(size); + sb.delete(sb.length()-2,sb.length()).append("]"); + return sb.toString(); + } + + public static void main(String[] args) { + Queue newQ = new Queue(); + for(int i=0;i<10;i++){ + newQ.enQueue(i); + } + System.err.println(newQ); + newQ.deQueue(); + System.err.println(newQ); + } + + +} diff --git a/group24/120509419/Stack.java b/group24/120509419/Stack.java new file mode 100644 index 0000000000..3ba85c6bcf --- /dev/null +++ b/group24/120509419/Stack.java @@ -0,0 +1,63 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +/** + * + * @author CJ + */ +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.size()==0; + } + + public int size() { + return elementData.size(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("ArrayList: ["); + for (int i = 0; i < elementData.size(); i++) { + sb.append(elementData.get(i)).append(", "); + } +// System.err.println(size); + sb.delete(sb.length()-2,sb.length()).append("]"); + return sb.toString(); + } + public static void main(String[] args) { + Stack newS = new Stack(); + for(int i=0;i<10;i++){ + newS.push(i); + } + System.err.println("Test push()"); + System.err.println(newS); + newS.pop(); + System.err.println("Test pop()"); + System.err.println(newS); + System.err.println("Test peek()"); + System.err.println(newS.peek()); + System.err.println(newS); + + } + +} diff --git a/group24/120509419/javaclass/ArrayUtil.java b/group24/120509419/javaclass/ArrayUtil.java new file mode 100644 index 0000000000..fc460454be --- /dev/null +++ b/group24/120509419/javaclass/ArrayUtil.java @@ -0,0 +1,237 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass; + +import java.util.Arrays; + +/** + * + * @author CJ + */ +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 totalLen = origin.length; + int[] revIntArr = new int[totalLen]; + for (int i = 0; i < totalLen; i++) { + revIntArr[i] = origin[totalLen - 1 - i]; + } + for (int i = 0; i < totalLen; i++) { + origin[i] = revIntArr[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 int[] removeZero(int[] oldArray) { + int totalLen = oldArray.length; + + int[] tmpArr = new int[totalLen]; + int nonZeroCount = 0; + for (int i : oldArray) { + if (i != 0) { + tmpArr[nonZeroCount++] = i; + } + } + return Arrays.copyOfRange(tmpArr, 0, nonZeroCount); + } + + /** + * 给定两个已经排序好的整形数组, 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 arrLen1 = array1.length; + int arrLen2 = array2.length; + int maxLen = arrLen1+arrLen2; + int[] mergedArr = new int[maxLen]; + int mergedC = 0; + int i = 0; + int j = 0; + while(i 1; + } + for(int i=2;i<=Math.sqrt(n);i++){ + if(n%i == 0) + return false; + } + return true; + } + + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + int[] perfectArr = new int[max]; + // int growSize = 100; + int Count = 0; + for(int i=2;iinNum){ + return false; + } + } + } + return sum == inNum; + } + + + + /** + * 用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(); + int loopMax = array.length-1; + for(int i=0;i parameters) throws FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, 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字段中。 + + */ + String strutsFilePath = getProRealPath(Struts.class) + File.separator + "struts.xml"; + System.out.println("Reading File: " + strutsFilePath); + + BufferedReader br = new BufferedReader(new FileReader(strutsFilePath)); + String inline; + String curActionName = null; + String className = null; + HashMap status2action = new HashMap(); + while ((inline = br.readLine()) != null) { + if (inline.contains("(.*?).*$", "$1\t$2").split("\t"); + status2action.put(info[0], info[1]); + } else if (inline.contains("")) { + if (actionName.equals(curActionName)) { + Class c = Class.forName(className); + Object curInstance = c.newInstance(); + + Method setNameMethod = c.getMethod("setName", String.class); + setNameMethod.invoke(curInstance, parameters.get("name")); + Method setPasswordMethod = c.getMethod("setPassword", String.class); + setPasswordMethod.invoke(curInstance, parameters.get("password")); + + Method excuteMethod = c.getMethod("execute"); + // 返回 sucess 或者 fail + String status =(String) excuteMethod.invoke(curInstance); + + String curJsp = status2action.get(status); + + Method getMessageMethod = c.getMethod("getMessage"); + + View curView = new View(); + curView.setJsp(curJsp); + Map curMap = new HashMap(); + curMap.put("message",(String) getMessageMethod.invoke(curInstance)); + curView.setParameters(curMap); + return curView; + + } + } + } + System.err.println("No Match Aciton"); + return null; + } + + public static String getProRealPath(Class inClass) { + URL url = inClass.getProtectionDomain().getCodeSource().getLocation(); + + String filePath = null; + try { + filePath = URLDecoder.decode(url.getPath(), "utf-8"); + } catch (Exception e) { + e.printStackTrace(); + } + if (filePath.endsWith(".jar")) { + filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1); + } + File file = new File(filePath); + filePath = file.getAbsolutePath(); + return filePath; + } + +} diff --git a/group24/120509419/javaclass/struts/View.java b/group24/120509419/javaclass/struts/View.java new file mode 100644 index 0000000000..700c376eaa --- /dev/null +++ b/group24/120509419/javaclass/struts/View.java @@ -0,0 +1,32 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaclass.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/group24/120509419/javaclass/struts/struts.xml b/group24/120509419/javaclass/struts/struts.xml new file mode 100644 index 0000000000..a6cdbfc4a4 --- /dev/null +++ b/group24/120509419/javaclass/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/group24/121111914/.gitignore b/group24/121111914/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group24/121111914/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group24/121111914/src/com/github/ipk2015/coding2017/basic/test/TestForDell.java b/group24/121111914/src/com/github/ipk2015/coding2017/basic/test/TestForDell.java new file mode 100644 index 0000000000..01d2c8d5fc --- /dev/null +++ b/group24/121111914/src/com/github/ipk2015/coding2017/basic/test/TestForDell.java @@ -0,0 +1,10 @@ +package com.github.ipk2015.coding2017.basic.test; + +public class TestForDell { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/group24/121111914/src/com/github/ipk2015/coding2017/coderising/array/ArrayUtil.java b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/array/ArrayUtil.java new file mode 100644 index 0000000000..d1ddfb6339 --- /dev/null +++ b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/array/ArrayUtil.java @@ -0,0 +1,229 @@ +package com.github.ipk2015.coding2017.coderising.array; + + + +import java.util.ArrayList; +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){ + int temp=0; + for(int i=0;i list= new ArrayList(); + for(int i=0;i=array[i+1]){ + throw new RuntimeException("不是排序好的数组"); + } + } + } + /** + * 把一个已经存满数据的数组 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 list=new ArrayList(); + list.add(1); + list.add(1); + int size=2; + int lastElement=2; + while(lastElement list=new ArrayList(); + list.add(2); + for(int i=3;i list=new ArrayList(); + for(int i=2;i parameters) throws Exception { + + /* + + 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(); + Document document = reader.read("src/com/github/ipk2015/coding2017/coderising/litestruts/struts.xml"); + Element rootElement = document.getRootElement(); + + Element actionElement=findElement(rootElement,"action","name",actionName); + Class armClass = Class.forName(actionElement.attributeValue("class")); + Object newInstance = armClass.newInstance(); + + setParameters(armClass,newInstance,parameters); + + Method exectueMethod = armClass.getMethod("execute"); + String exectueMethodResult = (String) exectueMethod.invoke(newInstance); + + View view=new View(); + Map viewParameters = getViewParameters(armClass,newInstance); + view.setParameters(viewParameters); + + Element resultElement=findElement(actionElement,"result","name",exectueMethodResult); + view.setJsp(resultElement.getStringValue()); + + return view; + } + + private static Element findElement(Element parent,String elementTag,String attributeName,String actionName){ + Element actionElement = null; + String nameAttributeValue=""; + List elements = parent.elements(elementTag); + for(Element element : elements){ + nameAttributeValue = element.attributeValue(attributeName); + if(nameAttributeValue.equals(actionName)){ + actionElement=element; + break; + } + } + return actionElement; + } + private static void setParameters(Class armClass,Object newInstance,Map parameters) throws Exception{ + Set> entrySet = parameters.entrySet(); + String entryKey=""; + String firstLetter=""; + Method method=null; + for(Entry entry:entrySet){ + entryKey=entry.getKey(); + firstLetter=entryKey.substring(0, 1); + entryKey=entryKey.replace(firstLetter,firstLetter.toUpperCase()); + method = armClass.getMethod("set"+entryKey, String.class); + method.invoke(newInstance, entry.getValue()); + } + } + private static Map getViewParameters(Class armClass,Object newInstance) throws Exception{ + Map map=new HashMap(); + Object getMethodReturn=null; + String methodName=""; + Method[] methods = armClass.getMethods(); + for(int i=0;i3 && methodName.startsWith("get")){ + getMethodReturn=methods[i].invoke(newInstance); + map.put(methodName.substring(3).toLowerCase(), getMethodReturn.toString()); + } + } + return map; + } +} diff --git a/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/StrutsTest.java b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..3f5f9bc98e --- /dev/null +++ b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/StrutsTest.java @@ -0,0 +1,61 @@ +package com.github.ipk2015.coding2017.coderising.litestruts; + + + +import static org.junit.Assert.fail; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +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 = null; + try { + view = Struts.runAction(actionName,params); + } catch (Exception e) { + // TODO Auto-generated catch block + fail("发生异常"); + e.printStackTrace(); + } + 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 = null; + try { + view = Struts.runAction(actionName,params); + } catch (Exception e) { + // TODO Auto-generated catch block + fail("发生异常"); + e.printStackTrace(); + } + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/View.java b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/View.java new file mode 100644 index 0000000000..26f7bddb17 --- /dev/null +++ b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/View.java @@ -0,0 +1,25 @@ +package com.github.ipk2015.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; + } +} diff --git a/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/struts.xml b/group24/121111914/src/com/github/ipk2015/coding2017/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..0c1df8c87c --- /dev/null +++ b/group24/121111914/src/com/github/ipk2015/coding2017/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/group24/1525619747/.gitignore b/group24/1525619747/.gitignore new file mode 100644 index 0000000000..5b4edb7bcb --- /dev/null +++ b/group24/1525619747/.gitignore @@ -0,0 +1,5 @@ +*bin/ + +.project +.classpath +.settings diff --git a/group24/1525619747/homework_20170312/src/com/basic/ArrayList.java b/group24/1525619747/homework_20170312/src/com/basic/ArrayList.java new file mode 100644 index 0000000000..008b390255 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/ArrayList.java @@ -0,0 +1,95 @@ +package com.basic; + +public class ArrayList implements List +{ + + private int size = 0; + + private final int MAXNSIZE = 100; + + private Object[] elementData = new Object[MAXNSIZE]; + + public void add(Object o) + { + if (size > MAXNSIZE) + { + String errorInfo = "Out of max size" + MAXNSIZE; + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + elementData[size++] = o; + } + + public void add(int index, Object o) + { + if (index >= size && size > 0) + { + String errorInfo = "Index to add: " + index + + " is out of current size: " + size; + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + for (int i = size; i > index; i--) + { + elementData[i] = elementData[i - 1]; + } + elementData[index] = o; + ++size; + } + + public Object get(int index) + { + if (index < 0 || index >= size) + { + String errorInfo = "Index to get: " + index + + " is invalid, current range: 0 - " + (size - 1); + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + return elementData[index]; + } + + public Object remove(int index) + { + if (index < 0 || index >= size) + { + String errorInfo = "Index to remove: " + index + + " is invalid, current range: 0 - " + (size - 1); + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + + Object o = elementData[index]; + for (int i = index; i < size - 1; i++) + { + elementData[i] = elementData[i + 1]; + } + elementData[size--] = null; + return o; + } + + public int size() + { + return size; + } + + public Iterator iterator() + { + return new Iterator() + { + + private int index = 0; + + public boolean hasNext() + { + return (index < size); + } + + public Object next() + { + if (hasNext()) + { + return elementData[index++]; + } + return null; + } + }; + } + +} diff --git a/group24/1525619747/homework_20170312/src/com/basic/BinaryTreeNode.java b/group24/1525619747/homework_20170312/src/com/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..63899d38ce --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/BinaryTreeNode.java @@ -0,0 +1,103 @@ +package com.basic; + +public class BinaryTreeNode +{ + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public BinaryTreeNode (Object data) + { + this.data = data; + left = null; + right = null; + } + + public BinaryTreeNode (Object data, BinaryTreeNode left, + BinaryTreeNode right) + { + this.data = data; + this.left = left; + this.right = 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) + { + if (((Integer) data) > ((Integer) o)) + { + if (left == null) + { + setLeft(new BinaryTreeNode(o)); + } + else + { + left.insert(o); + } + } + else + { + if (right == null) + { + setRight(new BinaryTreeNode(o)); + } + else + { + right.insert(o); + } + } + return this; + } + + /* + * 前序遍历 + */ + public void preOrderInterator() + { + if (left != null) + { + left.preOrderInterator(); + } + + System.out.print(data.toString() + " "); + + if (right != null) + { + right.preOrderInterator(); + } + } + +} diff --git a/group24/1525619747/homework_20170312/src/com/basic/Iterator.java b/group24/1525619747/homework_20170312/src/com/basic/Iterator.java new file mode 100644 index 0000000000..402b5346a5 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/Iterator.java @@ -0,0 +1,9 @@ +package com.basic; + +public interface Iterator +{ + public boolean hasNext(); + + public Object next(); + +} diff --git a/group24/1525619747/homework_20170312/src/com/basic/LinkedList.java b/group24/1525619747/homework_20170312/src/com/basic/LinkedList.java new file mode 100644 index 0000000000..e741421aad --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/LinkedList.java @@ -0,0 +1,498 @@ +package com.basic; + +public class LinkedList implements List +{ + + private Node head; + + public void add(Object o) + { + if (head == null) + { + head = new Node(o, null); + } + else + { + Node nodePointer = head; + while (nodePointer.next != null) + { + nodePointer = nodePointer.next; + } + nodePointer.next = new Node(o, null); + } + + } + + public void add(int index, Object o) + { + int size = size(); + if (index < 0 || index > size) + { + String errorInfo = "Invalid index to add:" + index + + " out of range: [0," + size + "]"; + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + int step = 0; + Node nodePointer = head; + while (step < index) + { + nodePointer = nodePointer.next; + ++step; + } + nodePointer.next = new Node(o, nodePointer.next); + } + + public Object get(int index) + { + int size = size(); + if (index < 0 || index > size) + { + String errorInfo = "Invalid index to get:" + index + + " out of range: [0," + size + "]"; + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + + int step = 0; + Node nodePointer = head; + while (step < index) + { + nodePointer = nodePointer.next; + ++step; + } + + return nodePointer.data; + } + + public Object remove(int index) + { + int size = size(); + if (index < 0 || index > size) + { + String errorInfo = "Invalid index to remove:" + index + + " out of range: [0," + size + "]"; + throw new ArrayIndexOutOfBoundsException(errorInfo); + } + + int step = 0; + Node nodePointer = head; + Node lastPointer = head; + + while (step < index) + { + lastPointer = nodePointer; + nodePointer = nodePointer.next; + ++step; + } + + Object o = null; + + if (lastPointer == nodePointer) + { + Node toDelete = head; + o = toDelete.data; + head = head.next; + toDelete = null; + } + else + { + o = nodePointer.data; + lastPointer.next = nodePointer.next; + nodePointer = null; + } + + return o; + } + + public int size() + { + int size = 0; + if (head != null) + { + ++size; + Node nodePointer = head; + while (nodePointer.next != null) + { + ++size; + nodePointer = nodePointer.next; + } + } + return size; + } + + public void addFirst(Object o) + { + if (head == null) + { + head = new Node(o, null); + return; + } + head = new Node(o, head); + } + + public void addLast(Object o) + { + if (head == null) + { + head = new Node(o, null); + return; + } + + Node nodePointer = head; + while (nodePointer.next != null) + { + nodePointer = nodePointer.next; + } + nodePointer.next = new Node(o, null); + } + + @SuppressWarnings ("unused") + public Object removeFirst() + { + if (head == null) + { + return null; + } + + Node toDelete = head; + Object o = head.data; + head = head.next; + toDelete = null; + + return o; + } + + public Object removeLast() + { + if (head == null) + { + return null; + } + + Node nodePointer = head; + Node lastPointer = head; + + while (nodePointer.next != null) + { + lastPointer = nodePointer; + nodePointer = nodePointer.next; + } + lastPointer.next = null; + Object o = nodePointer.data; + nodePointer = null; + + return o; + } + + public Iterator iterator() + { + return new Iterator() + { + + private Node nodePointer = head; + + public boolean hasNext() + { + // TODO Auto-generated method stub + return (nodePointer != null); + } + + public Object next() + { + // TODO Auto-generated method stub + if (hasNext()) + { + Object o = nodePointer.data; + nodePointer = nodePointer.next; + return o; + } + return null; + } + }; + } + + private static class Node + { + Object data; + Node next; + + public Node (Object o, Node n) + { + this.data = o; + this.next = n; + } + } + + /** + * 把该链表逆置 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() + { + if (head == null) + { + return; + } + + Node reverse = null; + while (size() > 0) + { + reverse = new Node(removeFirst(), reverse); + } + + head = reverse; + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + */ + @SuppressWarnings ("unused") + public void removeFirstHalf() + { + int removeLength = size() / 2; + int step = 0; + Node toDelete = null; + while (step < removeLength) + { + toDelete = head; + head = head.next; + toDelete = null; + ++step; + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) + { + int size = size(); + if (i >= size) + { + return; + } + Node nodePointer = head; + Node lastPointer = head; + int step = 0; + while (step < i) + { + lastPointer = nodePointer; + nodePointer = nodePointer.next; + ++step; + } + + step = 0; + Node toDelete = null; + if (lastPointer == head) + { + while (step < length) + { + toDelete = head; + head = head.next; + toDelete = null; + ++step; + } + } + else + { + while (step < length) + { + toDelete = nodePointer; + nodePointer = nodePointer.next; + toDelete = null; + ++step; + } + lastPointer.next = nodePointer; + } + + } + + /** + * 假定当前链表和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[] elements = new int[list.size()]; + Iterator it = list.iterator(); + int index = 0; + for (; it.hasNext();) + { + elements[index++] = (Integer) get((Integer) (it.next())); + } + return elements; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 从当前链表中中删除在list中出现的元素 + * + * @param list + */ + + public void subtract(LinkedList list) + { + if (head == null) + { + return; + } + Node nodePointer = head; + Node lastPointer = head; + Node toDelte = null; + while (nodePointer != null) + { + if (list.contain(nodePointer.data)) + { + if (nodePointer == head) + { + toDelte = head; + head = head.next; + toDelte = null; + nodePointer = head; + lastPointer = head; + } + else + { + toDelte = nodePointer; + lastPointer.next = nodePointer.next; + toDelte = null; + } + } + lastPointer = nodePointer; + nodePointer = nodePointer.next; + } + + } + + private boolean contain(Object o) + { + Node nodePointer = head; + while (nodePointer != null) + { + if (nodePointer.data.equals(o)) + { + return true; + } + nodePointer = nodePointer.next; + } + return false; + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() + { + Node nodePointer = head; + if (nodePointer.next == null) + { + return; + } + + Node toDelete = null; + while (nodePointer.next != null) + { + while (nodePointer.next != null + && nodePointer.data.equals(nodePointer.next.data)) + { // delete nodePointer.next + toDelete = nodePointer.next; + nodePointer.next = nodePointer.next.next; + toDelete = null; + } + nodePointer = nodePointer.next; + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) + { + Node nodePointer = head; + Node lastPointer = head; + if (nodePointer == null) + { + return; + } + while (nodePointer != null + && ((Integer) nodePointer.data) <= (new Integer(min))) + { + lastPointer = nodePointer; + nodePointer = nodePointer.next; + } + Node toDelete = null; + while (nodePointer != null + && ((Integer) nodePointer.data) < (new Integer(max))) + { + if (nodePointer == head) + { + toDelete = head; + head = head.next; + toDelete = null; + nodePointer = head; + lastPointer = head; + } + else + { + toDelete = nodePointer; + lastPointer.next = nodePointer.next; + nodePointer = nodePointer.next; + toDelete = null; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) + { + LinkedList linkedList = new LinkedList(); + Iterator it1 = iterator(); + Iterator it2 = list.iterator(); + Object o1 = null; + Object o2 = null; + + if (size() == 0 || list.size() == 0) + { + return null; + } + + o1 = it1.next(); + o2 = it2.next(); + + while (o1 != null && o2 != null) + { + // System.out.println(o1 + " " + o2); + if (((Integer) o1) == ((Integer) o2)) + { + linkedList.add(o1); + o1 = it1.next(); + o2 = it2.next(); + } + else + { + if (((Integer) o1) > ((Integer) o2)) + { + o2 = it2.next(); + } + else + { + o1 = it1.next(); + } + } + } + + return linkedList; + } +} diff --git a/group24/1525619747/homework_20170312/src/com/basic/List.java b/group24/1525619747/homework_20170312/src/com/basic/List.java new file mode 100644 index 0000000000..8892e795e9 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/List.java @@ -0,0 +1,14 @@ +package com.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/group24/1525619747/homework_20170312/src/com/basic/Queue.java b/group24/1525619747/homework_20170312/src/com/basic/Queue.java new file mode 100644 index 0000000000..b040c85722 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/Queue.java @@ -0,0 +1,26 @@ +package com.basic; + +public class Queue +{ + private LinkedList list = new LinkedList(); + + public void enQueue(Object o) + { + list.addLast(o); + } + + public Object deQueue() + { + return list.removeFirst(); + } + + public boolean isEmpty() + { + return (list.size() == 0); + } + + public int size() + { + return list.size(); + } +} diff --git a/group24/1525619747/homework_20170312/src/com/basic/Stack.java b/group24/1525619747/homework_20170312/src/com/basic/Stack.java new file mode 100644 index 0000000000..db7ada4c53 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/com/basic/Stack.java @@ -0,0 +1,31 @@ +package com.basic; + +public class Stack +{ + private ArrayList elementData = new ArrayList(); + + public void push(Object o) + { + elementData.add(0, o); + } + + public Object pop() + { + return elementData.remove(0); + } + + public Object peek() + { + return elementData.get(0); + } + + public boolean isEmpty() + { + return (elementData.size() == 0); + } + + public int size() + { + return elementData.size(); + } +} diff --git a/group24/1525619747/homework_20170312/src/testcase/TestArrayList.java b/group24/1525619747/homework_20170312/src/testcase/TestArrayList.java new file mode 100644 index 0000000000..134a541265 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/testcase/TestArrayList.java @@ -0,0 +1,199 @@ +package testcase; + +import static org.junit.Assert.*; + +import com.basic.ArrayList; +import com.basic.Iterator; + +import org.junit.Test; + +public class TestArrayList +{ + + @Test + public void testAdd() + { + ArrayList list = new ArrayList(); + try + { + list.add(3); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + assertTrue(list.get(0).equals(3)); + try + { + for (int i = 0; i < 100; i++) + { + list.add(i); + } + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + // System.out.println(e.getMessage()); + assertEquals("100", e.getMessage()); + } + + } + + /* + * test add(index, o) + */ + @Test + public void testIndexAdd() + { + ArrayList list = new ArrayList(); + try + { + for (int i = 0; i < 10; i++) + { + list.add(i); + } + list.add(3, 20); + list.add(0, 30); + + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + + // Iterator it = list.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + + assertTrue(list.get(0).equals(30)); + assertTrue(list.get(4).equals(20)); + assertTrue(list.get(5).equals(3)); + + try + { + for (int i = 0; i < 100; i++) + { + list.add(i, i); + } + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + // System.out.println(e.getMessage()); + assertEquals("100", e.getMessage()); + } + } + + /* + * test get(index) + */ + @Test + public void testGet() + { + ArrayList list = new ArrayList(); + try + { + for (int i = 0; i < 10; i++) + { + list.add(i); + } + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + try + { + list.get(0); + list.get(5); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + try + { + list.get(10); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + // System.out.println(e.getMessage()); + // System.out.println(list.size()); + String errorInfo = "Index to get: 10 is invalid, current range: 0 - " + + (list.size() - 1); + assertEquals(errorInfo, e.getMessage()); + } + } + + /* + * test remove(index) and size + */ + @Test + public void testRemove() + { + ArrayList list = new ArrayList(); + try + { + for (int i = 0; i < 10; i++) + { + list.add(i); + } + assertTrue(list.size() == 10); + list.remove(3); + assertTrue(list.size() == 9); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + assertFalse(list.get(3).equals(3)); + assertTrue(list.get(3).equals(4)); + + try + { + list.remove(-3); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + // System.out.println(e.getMessage()); + } + + try + { + list.remove(20); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + // System.out.println(e.getMessage()); + } + } + + @Test + public void testInterator() + { + ArrayList list = new ArrayList(); + try + { + for (int i = 0; i < 10; i++) + { + list.add(i); + } + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + + Iterator it = list.iterator(); + assertTrue(it.hasNext()); + assertTrue(it.next().equals(0)); + assertTrue(it.next().equals(1)); + assertTrue(it.next().equals(2)); + } + +} diff --git a/group24/1525619747/homework_20170312/src/testcase/TestBinaryTreeNode.java b/group24/1525619747/homework_20170312/src/testcase/TestBinaryTreeNode.java new file mode 100644 index 0000000000..472b9a7fb0 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/testcase/TestBinaryTreeNode.java @@ -0,0 +1,25 @@ +package testcase; + +import org.junit.Test; + +import com.basic.BinaryTreeNode; + +public class TestBinaryTreeNode +{ + @Test + public void testBinaryTree() + { + BinaryTreeNode binNode = new BinaryTreeNode(5); + binNode.insert(1); + binNode.insert(10); + binNode.insert(4); + binNode.insert(6); + binNode.insert(2); + binNode.insert(15); + binNode.insert(8); + + // 1 2 4 5 6 8 10 15 + binNode.preOrderInterator(); + } + +} diff --git a/group24/1525619747/homework_20170312/src/testcase/TestLinkedList.java b/group24/1525619747/homework_20170312/src/testcase/TestLinkedList.java new file mode 100644 index 0000000000..05ac118a90 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/testcase/TestLinkedList.java @@ -0,0 +1,414 @@ +package testcase; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.basic.Iterator; +import com.basic.LinkedList; + +public class TestLinkedList +{ + + /* + * test add() and size() + */ + @Test + public void testAdd() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + assertTrue(linkedList.size() == 2); + } + + @Test + public void testGet() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + assertTrue(linkedList.get(0).equals(3)); + assertFalse(linkedList.get(0).equals("hello world")); + assertTrue(linkedList.get(1).equals("hello world")); + + try + { + linkedList.get(-1); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + String errorInfo = "Invalid index to get:" + -1 + + " out of range: [0," + linkedList.size() + "]"; + assertTrue(e.getMessage().equals(errorInfo)); + // System.out.println(e.getMessage()); + } + } + + @Test + public void testRemove() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + linkedList.add(4); + linkedList.add("Leon Deng"); + + try + { + linkedList.remove(-1); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + String errorInfo = "Invalid index to remove:" + -1 + + " out of range: [0," + linkedList.size() + "]"; + assertTrue(e.getMessage().equals(errorInfo)); + } + + try + { + linkedList.remove(10); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNotNull(e); + String errorInfo = "Invalid index to remove:" + 10 + + " out of range: [0," + linkedList.size() + "]"; + assertTrue(e.getMessage().equals(errorInfo)); + } + + Object o = null; + try + { + o = linkedList.remove(0); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + assertTrue(o.equals(3)); + + try + { + o = linkedList.remove(2); + } + catch (ArrayIndexOutOfBoundsException e) + { + assertNull(e); + } + // System.out.println(o); + assertTrue(o.equals("Leon Deng")); + } + + @Test + public void testAddFirst() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + + linkedList.addFirst("Leon Deng"); + assertTrue(linkedList.get(0).equals("Leon Deng")); + assertTrue(linkedList.get(1).equals(3)); + } + + @Test + public void testAddLast() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + + linkedList.addLast("Leon Deng"); + assertTrue(linkedList.get(linkedList.size() - 1).equals("Leon Deng")); + } + + @Test + public void testRemoveFirst() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + + Object o = linkedList.removeFirst(); + assertTrue(o.equals(3)); + o = linkedList.removeFirst(); + assertTrue(o.equals("hello world")); + } + + @Test + public void testRemoveLast() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("hello world"); + linkedList.add("Leon Deng"); + + Object o = linkedList.removeLast(); + assertTrue(o.equals("Leon Deng")); + o = linkedList.removeLast(); + assertTrue(o.equals("hello world")); + } + + @Test + public void testInterator() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add("Leon Deng"); + + Iterator it = linkedList.iterator(); + assertTrue(it.hasNext()); + assertTrue(it.next().equals(3)); + assertTrue(it.hasNext()); + assertTrue(it.next().equals("Leon Deng")); + assertFalse(it.hasNext()); + } + + @Test + public void testReverse() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(3); + linkedList.add(4); + linkedList.add(5); + linkedList.add(6); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + // + // linkedList.reverse(); + // + // it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + + Object o1 = linkedList.get(0); + Object o2 = linkedList.get(linkedList.size() - 1); + + linkedList.reverse(); + + Object o3 = linkedList.get(0); + Object o4 = linkedList.get(linkedList.size() - 1); + + assertEquals(o1, o4); + assertEquals(o2, o3); + + linkedList.reverse(); + Object o5 = linkedList.get(0); + Object o6 = linkedList.get(linkedList.size() - 1); + + assertEquals(o1, o5); + assertEquals(o2, o6); + } + + @Test + public void testRemoveFirstHalf() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(5); + linkedList.add(7); + linkedList.add(8); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + + linkedList.removeFirstHalf(); + assertTrue(linkedList.get(0).equals(7)); + + linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(5); + linkedList.add(7); + linkedList.add(8); + linkedList.add(10); + + linkedList.removeFirstHalf(); + assertTrue(linkedList.get(2).equals(10)); + } + + @Test + public void testRemoveIndexLength() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(5); + linkedList.add(7); + linkedList.add(8); + linkedList.add(10); + + linkedList.remove(0, 2); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + assertTrue(linkedList.get(0).equals(7)); + + linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(5); + linkedList.add(7); + linkedList.add(8); + linkedList.add(10); + + linkedList.remove(2, 2); + assertTrue(linkedList.get(0).equals(2)); + assertTrue(linkedList.get(2).equals(10)); + + } + + @Test + public void testGetElements() + { + // 11->101->201->301->401->501->601->701 listB = 1->3->4->6 + LinkedList linkedList = new LinkedList(); + linkedList.add(11); + linkedList.add(101); + linkedList.add(201); + linkedList.add(301); + linkedList.add(401); + linkedList.add(501); + linkedList.add(601); + linkedList.add(701); + + LinkedList indexLinkedList = new LinkedList(); + indexLinkedList.add(1); + indexLinkedList.add(3); + indexLinkedList.add(4); + indexLinkedList.add(6); + + int[] elements = linkedList.getElements(indexLinkedList); + + // for (int i = 0; i < elements.length; i++) { + // System.out.print(elements[i] + " "); + // } + // System.out.println(); + + assertEquals(elements[0], linkedList.get(1)); + assertEquals(elements[1], linkedList.get(3)); + assertEquals(elements[2], linkedList.get(4)); + assertEquals(elements[3], linkedList.get(6)); + } + + @Test + public void testSubstract() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(11); + linkedList.add(101); + linkedList.add(201); + linkedList.add(301); + linkedList.add(401); + linkedList.add(501); + linkedList.add(601); + linkedList.add(701); + + LinkedList substractList = new LinkedList(); + substractList.add(11); + substractList.add(301); + substractList.add(404); + substractList.add(501); + substractList.add(701); + + linkedList.subtract(substractList); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + + assertFalse(linkedList.get(0).equals(11)); + assertTrue(linkedList.get(0).equals(101)); + } + + @Test + public void testRemoveDuplicateValues() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(3); + linkedList.add(4); + linkedList.add(4); + linkedList.add(5); + + linkedList.removeDuplicateValues(); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + + assertTrue(linkedList.get(0).equals(1)); + assertTrue(linkedList.get(1).equals(2)); + assertTrue(linkedList.get(4).equals(5)); + + } + + @Test + public void testRemoveRange() + { + LinkedList linkedList = new LinkedList(); + for (int i = 0; i < 10; i++) + { + linkedList.add(i); + } + + linkedList.removeRange(3, 7); + + // Iterator it = linkedList.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + assertTrue(linkedList.get(3).equals(3)); + assertTrue(linkedList.get(4).equals(7)); + } + + @Test + public void testIntersection() + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.add(5); + linkedList.add(6); + + LinkedList secondList = new LinkedList(); + secondList.add(1); + secondList.add(3); + secondList.add(5); + secondList.add(6); + + LinkedList intersection = linkedList.intersection(secondList); + // Iterator it = intersection.iterator(); + // for ( ; it.hasNext(); ) { + // System.out.print(it.next() + " "); + // } + // System.out.println(); + assertTrue(intersection.get(0).equals(1)); + assertTrue(intersection.get(1).equals(3)); + assertTrue(intersection.get(2).equals(5)); + assertTrue(intersection.get(3).equals(6)); + } + +} diff --git a/group24/1525619747/homework_20170312/src/testcase/TestQueue.java b/group24/1525619747/homework_20170312/src/testcase/TestQueue.java new file mode 100644 index 0000000000..390238efc9 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/testcase/TestQueue.java @@ -0,0 +1,33 @@ +package testcase; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.basic.Queue; + +public class TestQueue +{ + /* + * test enQueue() isEmpty() and size() deQueue + */ + @Test + public void testQueue() + { + Queue queue = new Queue(); + + assertTrue(queue.isEmpty()); + + for (int i = 10; i < 20; i++) + { + queue.enQueue(i); + } + + assertFalse(queue.isEmpty()); + assertTrue(queue.size() == 10); + + assertTrue(queue.deQueue().equals(10)); + assertTrue(queue.deQueue().equals(11)); + } + +} diff --git a/group24/1525619747/homework_20170312/src/testcase/TestStack.java b/group24/1525619747/homework_20170312/src/testcase/TestStack.java new file mode 100644 index 0000000000..2091577ec1 --- /dev/null +++ b/group24/1525619747/homework_20170312/src/testcase/TestStack.java @@ -0,0 +1,33 @@ +package testcase; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.basic.Stack; + +public class TestStack +{ + @Test + public void testStack() + { + Stack stack = new Stack(); + + assertTrue(stack.isEmpty()); + + for (int i = 10; i < 20; i++) + { + stack.push(i); + } + + assertFalse(stack.isEmpty()); + assertTrue(stack.size() == 10); + + assertTrue(stack.peek().equals(19)); + assertFalse(stack.peek().equals(10)); + + assertTrue(stack.pop().equals(19)); + assertTrue(stack.pop().equals(18)); + } + +} diff --git a/group24/1525619747/homework_20170319/src/com/basic/ArrayUtil.java b/group24/1525619747/homework_20170319/src/com/basic/ArrayUtil.java new file mode 100644 index 0000000000..9b4b81c12d --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/basic/ArrayUtil.java @@ -0,0 +1,312 @@ +package com.basic; + +import java.util.Collections; + +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 left = 0; + int right = length - 1; + int a = 0; + int b = 0; + while (left < right) + { + swap(origin, left++, right--); + } + } + + private void swap(int[] origin, int i, int j) + { + // TODO Auto-generated method stub + int tmp = origin[i]; + origin[i] = origin[j]; + origin[j] = 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 length = oldArray.length; + int[] newArray = new int[length]; + int[] zeroArray = new int[length]; + + int zIndex = 0; + int nzIndex = 0; + for (int i = 0; i < length; i++) + { + if (oldArray[i] == 0) + { + zeroArray[zIndex++] = oldArray[i]; + } + else + { + newArray[nzIndex++] = oldArray[i]; + } + } + + int[] newArray2 = new int[nzIndex]; + for (int i = 0; i < nzIndex; i++) + { + newArray2[i] = newArray[i]; + } + + return newArray2; + } + + /** + * 给定两个已经排序好的整形数组, 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]; + + int index1 = 0; + int index2 = 0; + int index3 = 0; + + while (index1 < length1 && index2 < length2) + { + + if (index3 > 0) + { + if (array3[index3 - 1] == array1[index1]) + { + ++index1; + continue; + } + if (array3[index3 - 1] == array2[index2]) + { + ++index2; + continue; + } + } + + if (array1[index1] == array2[index2]) + { + array3[index3++] = array1[index1]; + ++index1; + ++index2; + continue; + } + if (array1[index1] < array2[index2]) + { + array3[index3++] = array1[index1]; + ++index1; + continue; + } + if (array1[index1] > array2[index2]) + { + array3[index3++] = array2[index2]; + ++index2; + continue; + } + } + + while (index1 < length1) + { + array3[index3++] = array1[index1++]; + } + while (index2 < length2) + { + array3[index3++] = array1[index2++]; + } + + int[] newArray = new int[index3]; + for (int i = 0; i < index3; i++) + { + newArray[i] = array3[i]; + } + + 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 length = oldArray.length; + int[] newArr = new int[length + size]; + for (int i = 0; i < length; i++) + { + newArr[i] = oldArray[i]; + } + for (int i = length; i < length + size; i++) + { + newArr[i] = 0; + } + 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 null; + } + int[] arr = new int[max / 2]; + int a = 1; + int b = 1; + int c = 0; + + arr[0] = 1; + arr[1] = 1; + + int index = 2; + while (a + b < max) + { + arr[index++] = a + b; + c = b; + b = a + b; + a = c; + } + + int[] newArr = new int[index]; + for (int i = 0; i < index; i++) + { + newArr[i] = arr[i]; + } + + return newArr; + } + + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) + { + int size = max / 2 + 1; + int[] arr = new int[size]; + int index = 0; + for (int i = 2; i < max; i++) + { + if (isPrime(i)) + { + arr[index++] = i; + } + } + + int[] newArr = new int[index]; + for (int i = 0; i < index; i++) + { + newArr[i] = arr[i]; + } + + return newArr; + } + + public boolean isPrime(int i) + { + for (int j = 2; j < i / 2; j++) + { + if (i % j == 0) + { + return false; + } + } + return true; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) + { + int size = max / 2 + 1; + int[] arr = new int[size]; + int index = 0; + for (int i = 2; i < max; i++) + { + if (isPerfectNumber(i)) + { + arr[index++] = i; + } + } + + int[] newArr = new int[index]; + for (int i = 0; i < index; i++) + { + newArr[i] = arr[i]; + } + + return newArr; + } + + public boolean isPerfectNumber(int num) + { + int sum = 0; + for (int i = 1; i <= num / 2; i++) + { + if (num % i == 0) + { + sum += i; + } + } + // System.out.println("num: " + num + ", sum:" + sum); + return (num == sum); + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) + { + String str = ""; + int length = array.length; + for (int a : array) + { + str += a + seperator; + } + str = str.substring(0, str.length() - 1); + return str; + } + +} diff --git a/group24/1525619747/homework_20170319/src/com/struts/DomXmlHelper.java b/group24/1525619747/homework_20170319/src/com/struts/DomXmlHelper.java new file mode 100644 index 0000000000..31d27b592c --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/struts/DomXmlHelper.java @@ -0,0 +1,121 @@ +package com.struts; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +/** + * DOM方式解析xml + */ +public class DomXmlHelper +{ + + private Map kv = new HashMap(); + + public DomXmlHelper () throws DocumentException + { + fetchAttributes(); + } + + // 遍历当前节点下的所有节点 + private void listNodes(Element node, String loop, Map kv) + { + + // System.out.println("当前节点的名称:" + node.getName()); + if (loop.equals("")) + { + loop += node.getName(); + } + else + { + kv.put(loop, node.getName()); + loop += "-" + node.getName(); + } + + // 首先获取当前节点的所有属性节点 + List list = node.attributes(); + // 遍历属性节点 + for (Attribute attribute : list) + { + // System.out.println("属性 "+attribute.getName() +":" + + // attribute.getValue()); + kv.put(loop, attribute.getValue()); + loop += "-" + attribute.getValue(); + // System.out.println("loop: " + loop); + } + + // 如果当前节点内容不为空,则输出 + if (!(node.getTextTrim().equals(""))) + { + // System.out.println("内容 " + node.getName() + ":" + + // node.getText()); + kv.put(loop, node.getText()); + loop += "-" + node.getText(); + // System.out.println("loop: " + loop); + } + + // 同时迭代当前节点下面的所有子节点 + // 使用递归 + Iterator iterator = node.elementIterator(); + while (iterator.hasNext()) + { + Element e = iterator.next(); + listNodes(e, loop, kv); + } + } + + private void fetchAttributes() throws DocumentException + { + // 创建SAXReader对象 + SAXReader reader = new SAXReader(); + // 读取文件 转换成Document + Document document = (Document) reader.read(new File( + "./src/com/struts/struts.xml")); + + // 获取根节点元素对象 + Element root = ((org.dom4j.Document) document).getRootElement(); + + listNodes(root, "", kv); + + for (Map.Entry entity : kv.entrySet()) + { + // System.out.println("key: " + entity.getKey() + " , value: " + + // entity.getValue()); + } + } + + public String getActionView(String action, String method) + { + String key = "struts-action-" + action; + String className = kv.get(key); + key += "-" + className + "-result-" + method; + return kv.get(key); + } + + public String getActionClassByName(String action) + { + String key = "struts-action-" + action; + return kv.get(key); + } + + // public static void main(String[] args) throws DocumentException { + // DomXmlHelper dm = new DomXmlHelper(); + // System.out.println(dm.getActionClassByName("login")); + // System.out.println(dm.getActionView("login", "success")); + // System.out.println(dm.getActionView("login", "fail")); + // + // System.out.println(dm.getActionClassByName("logout")); + // System.out.println(dm.getActionView("logout", "success")); + // System.out.println(dm.getActionView("logout", "error")); + // } + +} diff --git a/group24/1525619747/homework_20170319/src/com/struts/LoginAction.java b/group24/1525619747/homework_20170319/src/com/struts/LoginAction.java new file mode 100644 index 0000000000..6d1d5a2ca6 --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/struts/LoginAction.java @@ -0,0 +1,51 @@ +package com.struts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * + * @author + * + */ +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() + { + System.out.println("name: " + name + " , password: " + password); + 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/group24/1525619747/homework_20170319/src/com/struts/Struts.java b/group24/1525619747/homework_20170319/src/com/struts/Struts.java new file mode 100644 index 0000000000..f0ff145909 --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/struts/Struts.java @@ -0,0 +1,94 @@ +package com.struts; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.dom4j.DocumentException; + +public class Struts +{ + + public static View runAction(String actionName, + Map parameters) throws DocumentException, + ClassNotFoundException, NoSuchMethodException, SecurityException, + InstantiationException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException, + NoSuchFieldException + { + + /* + * + * 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字段中。 + */ + + DomXmlHelper dx = new DomXmlHelper(); + String action = "login"; + String className = dx.getActionClassByName(action); + // System.out.println(className); + + Class class1 = null; + class1 = Class.forName(className); + // System.out.println("类名称 " + class1.getName()); + + if (class1 != null) + { + // 调用class1的setName方法, 待参数 + // 根据.class反射出来的类实例 + Object instance = class1.newInstance(); + + Method method = class1.getMethod("setName", String.class); + Object res1 = method.invoke(instance, "test"); + + method = class1.getMethod("setPassword", String.class); + Object res2 = method.invoke(instance, "1234"); + + // set attr + for (Map.Entry entity : parameters.entrySet()) + { + String attrName = entity.getKey(); + String attrValue = entity.getValue(); + + Field idF = class1.getDeclaredField(attrName); // 获取属性 + idF.setAccessible(true); // 使用反射机制可以打破封装性,导致了java对象的属性不安全。 + idF.set(instance, attrValue); // set + } + + View view = new View(); + + method = class1.getMethod("execute"); + Object res3 = method.invoke(instance); + // System.out.println(res3); + String jsp = dx.getActionView(action, res3.toString()); + view.setJsp(jsp); + + method = class1.getMethod("getMessage"); + Object res4 = method.invoke(instance); + // System.out.println(res4); + + Map map = new HashMap(); + map.put("message", res4.toString()); + + view.setParameters(map); + + return view; + } + + return null; + } + +} diff --git a/group24/1525619747/homework_20170319/src/com/struts/View.java b/group24/1525619747/homework_20170319/src/com/struts/View.java new file mode 100644 index 0000000000..b5b9e2802b --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/struts/View.java @@ -0,0 +1,31 @@ +package com.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/group24/1525619747/homework_20170319/src/com/struts/struts.xml b/group24/1525619747/homework_20170319/src/com/struts/struts.xml new file mode 100644 index 0000000000..a33fbd92bb --- /dev/null +++ b/group24/1525619747/homework_20170319/src/com/struts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/1525619747/homework_20170319/src/testcase/StrutsTest.java b/group24/1525619747/homework_20170319/src/testcase/StrutsTest.java new file mode 100644 index 0000000000..61ef07748f --- /dev/null +++ b/group24/1525619747/homework_20170319/src/testcase/StrutsTest.java @@ -0,0 +1,55 @@ +package testcase; + +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; + +import com.struts.Struts; +import com.struts.View; + +public class StrutsTest +{ + + @Test + public void testLoginActionSuccess() throws ClassNotFoundException, + NoSuchMethodException, SecurityException, InstantiationException, + IllegalAccessException, IllegalArgumentException, + InvocationTargetException, DocumentException, NoSuchFieldException + { + + 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 ClassNotFoundException, + NoSuchMethodException, SecurityException, InstantiationException, + IllegalAccessException, IllegalArgumentException, + InvocationTargetException, DocumentException, NoSuchFieldException + { + 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/group24/1525619747/homework_20170319/src/testcase/TestArrayUtil.java b/group24/1525619747/homework_20170319/src/testcase/TestArrayUtil.java new file mode 100644 index 0000000000..fffa56eac1 --- /dev/null +++ b/group24/1525619747/homework_20170319/src/testcase/TestArrayUtil.java @@ -0,0 +1,152 @@ +package testcase; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.basic.ArrayUtil; + +public class TestArrayUtil +{ + private void print_r(int[] a) + { + for (int i = 0; i < a.length; i++) + { + System.out.print(a[i] + " "); + } + System.out.println(); + + // int index = 0; + // while (a[index] != '\0') { + // System.out.print(a[index] + " "); + // ++index; + // } + // System.out.println(); + } + + @Test + public void testReverseArray() + { + ArrayUtil arrayUtil = new ArrayUtil(); + + int[] a = { 7, 9, 30, 3 }; + // print_r(a); + + arrayUtil.reverseArray(a); + // print_r(a); + assertTrue(a[0] == 3); + assertTrue(a[1] == 30); + assertTrue(a[3] == 7); + + int[] b = { 7, 9, 30, 3, 4 }; + // print_r(b); + + arrayUtil.reverseArray(b); + // print_r(b); + assertTrue(b[0] == 4); + assertTrue(b[1] == 3); + assertTrue(b[3] == 9); + assertTrue(b[2] == 30); + } + + @Test + public void testRemoveZero() + { + ArrayUtil arrayUtil = new ArrayUtil(); + + int[] oldArr = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 }; + int[] newArr = arrayUtil.removeZero(oldArr); + // print_r(newArr); + assertFalse(newArr[4] == 0); + assertTrue(newArr[4] == 6); + + } + + @Test + public void testMerge() + { + ArrayUtil arrayUtil = new ArrayUtil(); + + int[] a1 = { 3, 5, 7, 8 }; + int[] a2 = { 4, 5, 6, 7 }; + + int[] newArr = arrayUtil.merge(a1, a2); + // print_r(newArr); + assertTrue(newArr[0] == 3); + assertTrue(newArr[2] == 5); + assertTrue(newArr[3] == 6); + assertTrue(newArr[5] == 8); + } + + @Test + public void testGrow() + { + ArrayUtil arrayUtil = new ArrayUtil(); + + int[] a1 = { 3, 5, 7, 8 }; + a1 = arrayUtil.grow(a1, 3); + // print_r(a1); + assertTrue(a1[0] == 3); + assertTrue(a1[2] == 7); + assertTrue(a1[3] == 8); + assertTrue(a1[4] == 0); + assertTrue(a1[5] == 0); + assertTrue(a1[6] == 0); + + } + + @Test + public void testFibonacci() + { + ArrayUtil arrayUtil = new ArrayUtil(); + int max = 100; + int[] arr = arrayUtil.fibonacci(max); + // print_r(arr); + + assertNotNull(arr); + int index = (int) (Math.random() * arr.length); + assertTrue(arr[index] < max); + + arr = arrayUtil.fibonacci(1); + assertNull(arr); + } + + @Test + public void testGetPrimes() + { + ArrayUtil arrayUtil = new ArrayUtil(); + int max = 23; + int[] arr = arrayUtil.getPrimes(max); + // print_r(arr); + + int index = (int) (Math.random() * arr.length); + assertTrue(arr[index] < max); + assertTrue(arrayUtil.isPrime(arr[index])); + + } + + @Test + public void testGetPerfectNumbers() + { + ArrayUtil arrayUtil = new ArrayUtil(); + int max = 300; + int[] arr = arrayUtil.getPerfectNumbers(max); + // print_r(arr); + + int index = (int) (Math.random() * arr.length); + assertTrue(arr[index] < max); + assertTrue(arrayUtil.isPerfectNumber(arr[index])); + + } + + @Test + public void testJoin() + { + ArrayUtil arrayUtil = new ArrayUtil(); + int[] a = { 3, 8, 9 }; + String str = arrayUtil.join(a, "-"); + // System.out.println(str); + assertTrue(str.equals("3-8-9")); + } + +} diff --git a/group24/315863321/.gitignore b/group24/315863321/.gitignore new file mode 100644 index 0000000000..5e57f14b91 --- /dev/null +++ b/group24/315863321/.gitignore @@ -0,0 +1,3 @@ +*.xml +*.iml +*.jsp \ No newline at end of file diff --git a/group24/315863321/src/main/java/com/johnChnia/coderising2017/array/ArrayUtil.java b/group24/315863321/src/main/java/com/johnChnia/coderising2017/array/ArrayUtil.java new file mode 100644 index 0000000000..3126dafc53 --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coderising2017/array/ArrayUtil.java @@ -0,0 +1,227 @@ +package com.johnChnia.coderising2017.array; + +import com.johnChnia.coding2017.basic.Queue; +import com.johnChnia.coding2017.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; + for (int i = 0; i < length / 2; i++) { + int start = i; + int end = length - 1 - i; + int temp = origin[start]; + origin[start] = 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) { + Queue notZeroQueue = new Queue(); + for (int element : + oldArray) { + if (element != 0) { + notZeroQueue.add(element); + } + } + int[] newArray = new int[notZeroQueue.size()]; + for (int index = 0; index < newArray.length; index++) { + newArray[index] = (int) notZeroQueue.remove(); + } + 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 array1List = new ArrayList<>(); + for (int element : + array1) { + array1List.add(element); + } + for (int i = 0; i < array2.length; i++) { + int inserted = array2[i]; + for (int j = 0; j < array1List.size(); j++) { + if (array1List.indexOf(inserted) != -1) { + break; + } else if (inserted < array1List.get(j)) { + array1List.add(j, inserted); + } else if (j == array1List.size() - 1) { + array1List.add(inserted); + } + } + } + int[] newArray = new int[array1List.size()]; + for (int i = 0; i < array1List.size(); i++) { + newArray[i] = array1List.get(i); + } + + 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[] copy = new int[oldArray.length + size]; + System.arraycopy(oldArray, 0, copy, 0, + Math.min(oldArray.length, copy.length)); + return copy; + } + + /** + * 斐波那契数列为: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[] newArray; + if (max == 1) { + newArray = new int[0]; + } else if (max == 2) { + newArray = new int[]{1, 1}; + } else { + int next; + ArrayList arrayList = new ArrayList<>(); + arrayList.add(1); + arrayList.add(1); + for (int i = 0; i < arrayList.size(); i++) { + next = arrayList.get(i) + arrayList.get(i + 1); + if (next < max) { + arrayList.add(next); + } else { + break; + } + } + + newArray = new int[arrayList.size()]; + for (int i = 0; i < arrayList.size(); i++) { + newArray[i] = arrayList.get(i); + } + } + + return newArray; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + ArrayList arrayList = new ArrayList<>(); + for (int i = 0; i < max; i++) { + if (i <= 1) { + continue; + } + boolean flag = true; + for (int j = 2; j <= Math.sqrt(i); j++) { + if (i % j == 0) { + flag = false; + } + } + if (flag) { + arrayList.add(i); + } + } + int[] newArray = new int[arrayList.size()]; + for (int i = 0; i < arrayList.size(); i++) { + newArray[i] = arrayList.get(i); + } + return newArray; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + ArrayList arrayList = new ArrayList<>(); + 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) { + arrayList.add(i); + } + } + + int[] newArray = new int[arrayList.size()]; + for (int i = 0; i < arrayList.size(); i++) { + newArray[i] = arrayList.get(i); + } + + return newArray; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * + * @param array + * @param seperator + * @return + */ + public String join(int[] array, String seperator) { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < array.length-1; i++) { + stringBuilder.append(array[i]); + stringBuilder.append(seperator); + } + stringBuilder.append(array[array.length-1]); + return stringBuilder.toString(); + } + + + public void printArray(int[] array) { + for (int element : + array) { + System.out.print(element + ", "); + } + } + +} diff --git a/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/LoginAction.java b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/LoginAction.java new file mode 100644 index 0000000000..1bab950b95 --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/LoginAction.java @@ -0,0 +1,41 @@ +package com.johnChnia.coderising2017.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/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/Struts.java b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/Struts.java new file mode 100644 index 0000000000..8c92a3a49b --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/Struts.java @@ -0,0 +1,111 @@ +package com.johnChnia.coderising2017.litestruts; + +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.io.File; +import java.lang.reflect.Constructor; +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; + + +public class Struts { + + public static View runAction(String actionName, Map parameters) throws Exception { + + /* + + 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(); + Document document = null; + document = reader.read(new File("target/classes/struts.xml")); + Element node = document.getRootElement(); + List elements = node.elements("action"); + + Class action = null; + Object actionInstance = null; + Method[] methods = null; + View view = null; + for (Element element : + elements) { + if (element.attribute("name").getValue().equals(actionName)) { + action = Class.forName(element.attribute("class").getValue()); + Constructor constructor = action.getConstructor(null); + actionInstance = constructor.newInstance(null); + + + methods = action.getDeclaredMethods(); + Iterator mapIterator = parameters.entrySet().iterator(); + while (mapIterator.hasNext()) { + Map.Entry entry = (Map.Entry) mapIterator.next(); + Object key = entry.getKey(); + Object value = entry.getValue(); + for (Method method : + methods) { + if (method.getName().equalsIgnoreCase("set" + key)) { + method.invoke(actionInstance, value); + break; + } + } + } + + + Method method = action.getMethod("execute", null); + String resultName = (String) method.invoke(actionInstance, null); + + + Map map = new HashMap<>(); + Field[] fields = action.getDeclaredFields(); + for (Field field : + fields) { + String fieldName = field.getName(); + String methodName = "get" + + fieldName.substring(0, 1).toUpperCase() + + fieldName.substring(1); + map.put(fieldName, + (String) action.getMethod(methodName, null) + .invoke(actionInstance, null)); + } + + String jsp = null; + Iterator xmlIterator = element.elementIterator(); + while (xmlIterator.hasNext()) { + Element e = xmlIterator.next(); + if (e.attribute("name").getValue().equals(resultName)) { + jsp = e.getTextTrim(); + } + } + view = new View(); + view.setParameters(map); + view.setJsp(jsp); + } + } + + + return view; + } + + +} diff --git a/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/View.java b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/View.java new file mode 100644 index 0000000000..b6bab92926 --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coderising2017/litestruts/View.java @@ -0,0 +1,23 @@ +package com.johnChnia.coderising2017.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/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/ArrayList.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/ArrayList.java index 4881c6518c..8c4b8807be 100644 --- a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/ArrayList.java +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/ArrayList.java @@ -4,12 +4,21 @@ /** * Created by john on 2017/3/8. - * @// TODO: 2017/3/15 支持泛型 + * @// TODO: 2017/4/1 实现Iterator 接口 */ -public class ArrayList { - private int[] elementData; +public class ArrayList implements List { + private Object[] elementData; private int size = 0; + private static final int DEFAULTCAPACITY = 10; + + + /** + * Constructs an list with the default capacity. + */ + public ArrayList() { + elementData = new Object[DEFAULTCAPACITY]; + } /** * Constructs an list with the specified initial capacity. @@ -20,7 +29,7 @@ public class ArrayList { */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { - elementData = new int[initialCapacity]; + elementData = new Object[initialCapacity]; } else { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); @@ -34,10 +43,9 @@ public ArrayList(int initialCapacity) { * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ - public int get(int index) { + public E get(int index) { rangeCheck(index); - rangeCheckForAdd(index); - return elementData[index]; + return (E) elementData[index]; } @@ -46,7 +54,7 @@ public int get(int index) { * * @param element element to be appended to this list */ - public void add(int element) { + public void add(E element) { ensureCapacityInternal(size + 1); elementData[size++] = element; } @@ -61,7 +69,7 @@ public void add(int element) { * @param index index at which the specified element is to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ - public void add(int element, int index) { + public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1, @@ -79,16 +87,36 @@ public void add(int element, int index) { * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ - public int remove(int index) { + public E remove(int index) { rangeCheckForAdd(index); - int oldValue = elementData[index]; + Object oldValue = elementData[index]; int numMoved = size() - index - 1; if (numMoved > 0) { System.arraycopy(elementData, index + 1, elementData, index, numMoved); } - elementData[--size] = 0; // let jc to clear - return oldValue; + elementData[--size] = null; // let jc to clear + return (E) oldValue; + } + + /** + * Returns the index of the first occurrence of the specified element + * in this list, or -1 if this list does not contain the element. + * More formally, returns the lowest index i such that + * (o==null ? get(i)==null : o.equals(get(i))), + * or -1 if there is no such index. + */ + 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; } /** @@ -115,7 +143,8 @@ public int size() { * number of elements specified by the double length of list. */ private void grow() { - elementData = Arrays.copyOf(elementData, 2 * elementData.length); + elementData = Arrays.copyOf(elementData, + 2 * elementData.length); } public String toString() { @@ -134,11 +163,15 @@ private void ensureCapacityInternal(int minCapacity) { grow(); } + public Object[] toArray() { + return Arrays.copyOf(elementData, size()); + } + /** * A version of rangeCheck used by add and addAll. */ private void rangeCheckForAdd(int index) { - if (index > elementData.length - 1 || index < 0) { + if (index > size() - 1 || index < 0) { throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } } @@ -159,7 +192,7 @@ private String outOfBoundsMsg(int index) { * which throws an ArrayIndexOutOfBoundsException if index is negative. */ private void rangeCheck(int index) { - if (index >= size) { + if (index >= size()) { throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } } diff --git a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/BinarySearchTree.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/BinarySearchTree.java new file mode 100644 index 0000000000..48d3e41b12 --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/BinarySearchTree.java @@ -0,0 +1,124 @@ +package com.johnChnia.coding2017.basic; + +/** + * Created by john on 2017/3/13. + */ +public class BinarySearchTree { + + + /** + * The root node of tree. + */ + public BstNode root; + + private Queue q = new Queue(); + + + private static class BstNode { + private int data; + private BstNode left; + private BstNode right; + + @Override + public String toString() { + return String.valueOf(data); + } + } + + /** + * create an BinarySearchTree. + * + * @param root root node of tree + * @param data stored element + * @return binarySearchTree + */ + public BstNode insert(BstNode root, int data) { + if (root == null) { + root = getNewBstNode(data); + if (this.root == null) { + this.root = root; + } + return root; + } + if (data <= root.data) { + root.left = insert(root.left, data); + } else { + root.right = insert(root.right, data); + } + return root; + } + + private BstNode getNewBstNode(int data) { + BstNode node = new BstNode(); + node.data = data; + node.left = null; + node.right = null; + return node; + } + + /** + * Returns the minimum value in the tree. + * + * @param root root node of the tree。 + * @return the minimum value in the tree + * @throws IllegalArgumentException if root is null. + */ + public int findMin(BstNode root) { + int min; + if (root == null) { + throw new IllegalArgumentException("tree is empty"); + } else if (root.left == null) { + min = root.data; + } else { + min = findMin(root.left); + } + return min; + } + + /** + * Returns the maximum value in the tree. + * + * @param root root node of the tree。 + * @return the maximum value in the tree + * @throws IllegalArgumentException if root is null. + */ + public int findMax(BstNode root) { + int max; + if (root == null) { + throw new IllegalArgumentException("tree is empty"); + } else if (root.right == null) { + max = root.data; + } else { + max = findMax(root.right); + } + return max; + } + + + /** + * Traverse each node from left to right. + * + * @param root root node of the tree + */ + public void LevelOrder(BstNode root) { + if (root == null) { + return; + } + q.add(root); + while (!q.empty()) { + BstNode current = (BstNode) q.peek(); + if (current.left != null) { + q.add(current.left); + } + if (current.right != null) { + q.add(current.right); + } + q.remove(); + } + } + + public BstNode getRoot() { + return root; + } + +} diff --git a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/LinkedList.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/LinkedList.java index f2825659b9..a91f03573a 100644 --- a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/LinkedList.java +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/LinkedList.java @@ -5,12 +5,12 @@ /** * Created by john on 2017/3/9. * - * @// TODO: 2017/3/15 支持泛型 + * @// TODO: 2017/4/1 支持Iterator */ -public class LinkedList { +public class LinkedList implements List { - private Node first = null; + private Node first = null; private int size = 0; /** @@ -20,10 +20,10 @@ public LinkedList() { } - private static class Node { - int element; - Node next; - Node prev; + private static class Node { + T element; + Node next; + Node prev; } /** @@ -31,13 +31,13 @@ private static class Node { * * @param element element to be appended to this list */ - public void add(int element) { - Node newNode = new Node(); + public void add(E element) { + Node newNode = new Node<>(); if (first == null) { addWhenListIsEmpty(newNode, element); return; } - Node last = first; + Node last = first; while (last.next != null) last = last.next; last.next = newNode; @@ -47,7 +47,7 @@ public void add(int element) { size++; } - private void addWhenListIsEmpty(Node newNode, int element) { + private void addWhenListIsEmpty(Node newNode, E element) { first = newNode; first.element = element; first.next = null; @@ -60,8 +60,8 @@ private void addWhenListIsEmpty(Node newNode, int element) { * * @param element the element to add */ - public void addFirst(int element) { - Node newNode = new Node(); + public void addFirst(E element) { + Node newNode = new Node<>(); if (first == null) { addWhenListIsEmpty(newNode, element); return; @@ -85,7 +85,7 @@ public void addFirst(int element) { * @param element element to be inserted. * @throws RuntimeException if list size less than 2. */ - public void add(int index, int element) { + public void add(int index, E element) { if (size() < 2) throw new RuntimeException("list size should greater than or equal to 2"); isElementIndex(index); @@ -93,8 +93,8 @@ public void add(int index, int element) { addFirst(element); return; } else { - Node temp = new Node(); - Node temp2 = first; + Node temp = new Node<>(); + Node temp2 = first; for (int i = 0; i < index; i++) { temp2 = temp2.next; } @@ -118,11 +118,11 @@ public void add(int index, int element) { public void remove() { if (size == 0) throw new RuntimeException("linkList size should greater than or equal to 1"); - Node next = first.next; + Node next = first.next; if (next == null) { first = null; } else { - Node last = first; + Node last = first; while (last.next != null) last = last.next; last.prev.next = null; @@ -132,18 +132,27 @@ public void remove() { } + /** + * @param index + * @return + * @// TODO: 2018/3/14 if i am happy, i will implement it right now! + */ + public E remove(int index) { + return null; + } + /** * Removes and returns the first element from this list. * * @return the first element from this list */ - public int removeFirst() { - Node f = first; + public E removeFirst() { + Node f = first; if (f == null) throw new NoSuchElementException(); - int element = f.element; - Node next = first.next; - first.element = 0; + E element = f.element; + Node next = first.next; + first.element = null; first.next = null; // help GC first = next; @@ -160,9 +169,9 @@ public int removeFirst() { * @param index index of the element to return * @return the element at the specified position in this list */ - public int get(int index) { + public E get(int index) { checkElementIndex(index); - Node node = first; + Node node = first; if (index == 0) { return first.element; } @@ -178,8 +187,8 @@ public int get(int index) { * @return the first element in this list * @throws NoSuchElementException if this list is empty */ - public int getFirst() { - final Node f = first; + public E getFirst() { + final Node f = first; if (f == null) throw new NoSuchElementException(); return f.element; @@ -211,7 +220,7 @@ private boolean isElementIndex(int index) { public String toString() { StringBuilder sb = new StringBuilder(); sb.append(first.element); - Node temp = first; + Node temp = first; while (temp.next != null) { temp = temp.next; sb.append("→"); diff --git a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/List.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/List.java new file mode 100644 index 0000000000..6d5a8b01df --- /dev/null +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/List.java @@ -0,0 +1,16 @@ +package com.johnChnia.coding2017.basic; + +/** + * Created by john on 2017/3/12. + */ +public interface List { + public void add(E o); + + public void add(int index, E o); + + public E get(int index); + + public E remove(int index); + + public int size(); +} diff --git a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Queue.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Queue.java index 4fd2558ea3..4d8449a8eb 100644 --- a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Queue.java +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Queue.java @@ -4,17 +4,17 @@ /** * Created by john on 2017/3/10. - * @// TODO: 2017/3/15 支持泛型 + * @// TODO: 2017/4/1 实现Iterator */ -public class Queue { +public class Queue { - private ArrayList arrayList; + private ArrayList arrayList; /** * Constructs an queue using 10 capacity of ArrayList. */ public Queue() { - arrayList = new ArrayList(10); + arrayList = new ArrayList<>(); } @@ -26,7 +26,7 @@ public Queue() { * @param element the element to add * @return {@code true} */ - public boolean add(int element) { + public boolean add(E element) { arrayList.add(element); return true; } @@ -38,7 +38,7 @@ public boolean add(int element) { * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ - public int remove() { + public E remove() { if (arrayList.empty()) throw new NoSuchElementException(emptyMsg()); return arrayList.remove(0); @@ -52,7 +52,7 @@ public int remove() { * * @return the head of this queue, or {@code 0} if this queue is empty */ - public int peek() { + public Object peek() { if (arrayList.empty()) return 0; return arrayList.get(0); @@ -80,4 +80,8 @@ public int size() { private String emptyMsg() { return "Size: " + size(); } + + public boolean empty() { + return arrayList.size() == 0; + } } diff --git a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Stack.java b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Stack.java index e11be853f9..f43ea52397 100644 --- a/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Stack.java +++ b/group24/315863321/src/main/java/com/johnChnia/coding2017/basic/Stack.java @@ -4,16 +4,15 @@ /** * Created by john on 2017/3/10. - * @// TODO: 2017/3/15 支持泛型 */ -public class Stack { - private LinkedList linkList; +public class Stack { + private LinkedList linkList; /** * Creates an empty Stack. */ public Stack() { - linkList = new LinkedList(); + linkList = new LinkedList<>(); } @@ -22,7 +21,7 @@ public Stack() { * * @param element the element to be pushed onto this stack. */ - public void push(int element) { + public void push(E element) { linkList.addFirst(element); } @@ -33,7 +32,7 @@ public void push(int element) { * @return The object at the top of this stack. * @throws EmptyStackException if this stack is empty. */ - public int pop() { + public E pop() { if (empty()) { throw new EmptyStackException(); } @@ -47,7 +46,7 @@ public int pop() { * @return the object at the top of this stack. * @throws EmptyStackException if this stack is empty. */ - public int peek() { + public E peek() { if (empty()) { throw new EmptyStackException(); } @@ -58,7 +57,7 @@ public int peek() { * Tests if this stack is empty. * * @return true if and only if this stack contains - * no elements; false otherwise. + * no elements; false otherwise. */ public boolean empty() { return linkList.size() == 0; diff --git a/group24/315863321/src/test/java/com/johnChnia/coderising2017/array/ArrayUtilTest.java b/group24/315863321/src/test/java/com/johnChnia/coderising2017/array/ArrayUtilTest.java new file mode 100644 index 0000000000..9b730c19e5 --- /dev/null +++ b/group24/315863321/src/test/java/com/johnChnia/coderising2017/array/ArrayUtilTest.java @@ -0,0 +1,114 @@ +package com.johnChnia.coderising2017.array; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.junit.MatcherAssert.assertThat; + +/** + * Created by john on 2017/3/16. + */ +public class ArrayUtilTest { + + private ArrayUtil arrayUtil; + private int[] array1; + private int[] array2; + private int[] array3; + private int[] array4; + private int[] array5; + private int[] array6; + + @Before + public void setUp() throws Exception { + arrayUtil = new ArrayUtil(); + array1 = new int[]{7, 9, 30, 3}; + array2 = new int[]{1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5}; + array3 = new int[]{3, 5, 7, 8}; + array4 = new int[]{4, 5, 6, 7}; + array5 = new int[]{2, 3, 6}; + array6 = new int[]{2, 3, 5, 7, 11, 13, 17, 19}; + } + + @Test + public void testReverseArray() throws Exception { + arrayUtil.reverseArray(array1); + assertThat(array1[0], equalTo(3)); + assertThat(array1[1], equalTo(30)); + assertThat(array1[2], equalTo(9)); + assertThat(array1[3], equalTo(7)); + } + + @Test + public void testRemoveZero() throws Exception { + int[] newArray = arrayUtil.removeZero(array2); + for (int element : + newArray) { + assertThat(element, not(0)); + } + } + + @Test + public void testMerge() throws Exception { + int[] newArray = arrayUtil.merge(array3, array4); + assertThat(newArray[0], equalTo(3)); + assertThat(newArray[1], equalTo(4)); + assertThat(newArray[2], equalTo(5)); + assertThat(newArray[3], equalTo(6)); + assertThat(newArray[4], equalTo(7)); + assertThat(newArray[5], equalTo(8)); + } + + @Test + public void testGrow() throws Exception { + int[] newArray = arrayUtil.grow(array5, 3); + assertThat(newArray[0], equalTo(2)); + assertThat(newArray[1], equalTo(3)); + assertThat(newArray[2], equalTo(6)); + assertThat(newArray[3], equalTo(0)); + assertThat(newArray[4], equalTo(0)); + assertThat(newArray[5], equalTo(0)); + } + + @Test + public void testFibonacci() throws Exception { + int[] newArray = arrayUtil.fibonacci(15); + assertThat(newArray[0], equalTo(1)); + assertThat(newArray[1], equalTo(1)); + assertThat(newArray[2], equalTo(2)); + assertThat(newArray[3], equalTo(3)); + assertThat(newArray[4], equalTo(5)); + assertThat(newArray[5], equalTo(8)); + assertThat(newArray[6], equalTo(13)); + } + + @Test + public void testGetPrimes() throws Exception { + int[] newArray = arrayUtil.getPrimes(23); + assertThat(newArray[0], equalTo(2)); + assertThat(newArray[1], equalTo(3)); + assertThat(newArray[2], equalTo(5)); + assertThat(newArray[3], equalTo(7)); + assertThat(newArray[4], equalTo(11)); + assertThat(newArray[5], equalTo(13)); + assertThat(newArray[6], equalTo(17)); + assertThat(newArray[7], equalTo(19)); + } + + @Test + public void testGetPerfectNumbers() throws Exception { + int[] newArray = arrayUtil.getPerfectNumbers(100); + assertThat(newArray.length, equalTo(2)); + assertThat(newArray[0], equalTo(6)); + assertThat(newArray[1], equalTo(28)); + } + + @Test + public void testJoin() throws Exception { + assertThat(arrayUtil.join(array6, "-"), + containsString("2-3-5-7-11-13-17-19")); + } + +} \ No newline at end of file diff --git a/group24/315863321/src/test/java/com/johnChnia/coderising2017/litestruts/StrutsTest.java b/group24/315863321/src/test/java/com/johnChnia/coderising2017/litestruts/StrutsTest.java new file mode 100644 index 0000000000..d333db7d10 --- /dev/null +++ b/group24/315863321/src/test/java/com/johnChnia/coderising2017/litestruts/StrutsTest.java @@ -0,0 +1,39 @@ +package com.johnChnia.coderising2017.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +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 = com.johnChnia.coderising2017.litestruts.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 = com.johnChnia.coderising2017.litestruts.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/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/ArrayListTest.java b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/ArrayListTest.java similarity index 68% rename from group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/ArrayListTest.java rename to group24/315863321/src/test/java/com/johnChnia/coding2017/basic/ArrayListTest.java index 13c81724ad..e0df250c37 100644 --- a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/ArrayListTest.java +++ b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/ArrayListTest.java @@ -1,6 +1,5 @@ -package com.johnChnia.coding2017.basic.test; +package com.johnChnia.coding2017.basic; -import com.johnChnia.coding2017.basic.ArrayList; import org.junit.Before; import org.junit.Test; @@ -12,17 +11,18 @@ */ public class ArrayListTest { - private ArrayList arrayList1; - private ArrayList arrayList2; - private ArrayList arrayList3; - private ArrayList arrayList4; + private ArrayList arrayList1; + private ArrayList arrayList2; + private ArrayList arrayList3; + private ArrayList arrayList4; + private ArrayList arrayList5; @Before public void setUp() throws Exception { - arrayList1 = new ArrayList(3); - arrayList2 = new ArrayList(3); - arrayList3 = new ArrayList(3); - arrayList4 = new ArrayList(3); + arrayList1 = new ArrayList<>(3); + arrayList2 = new ArrayList<>(3); + arrayList3 = new ArrayList<>(3); + arrayList4 = new ArrayList<>(3); } @Test @@ -44,7 +44,7 @@ public void testAddElementByIndex() { for (int i = 0; i < 3; i++) { arrayList3.add(10); } - arrayList3.add(1000, 1); + arrayList3.add(1, 1000); assertThat(arrayList3.get(1), equalTo(1000)); } @@ -53,9 +53,11 @@ public void testRemoveElementByIndex() { for (int i = 0; i < 6; i++) { arrayList4.add(i); } - int removed = arrayList4.remove(4); + Object removed = arrayList4.remove(4); System.out.println(arrayList4); assertThat(removed, equalTo(4)); assertThat(arrayList4.size(), equalTo(5)); } + + } diff --git a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/BinarySearchTreeTest.java b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/BinarySearchTreeTest.java new file mode 100644 index 0000000000..d756c31198 --- /dev/null +++ b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/BinarySearchTreeTest.java @@ -0,0 +1,37 @@ +package com.johnChnia.coding2017.basic; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.junit.MatcherAssert.assertThat; + +/** + * Created by john on 2017/3/14. + */ +public class BinarySearchTreeTest { + + private BinarySearchTree bst; + + @Before + public void setUp() throws Exception { + bst = new BinarySearchTree(); + bst.insert(bst.getRoot(), 10); + bst.insert(bst.getRoot(), 20); + bst.insert(bst.getRoot(), 9); + bst.insert(bst.getRoot(), 11); + bst.insert(bst.getRoot(), 12); + } + + @Test + public void testFindMin() throws Exception { + assertThat(bst.findMin(bst.getRoot()), equalTo(9)); + + } + + @Test + public void testFindMax() throws Exception { + assertThat(bst.findMax(bst.getRoot()), equalTo(20)); + } + +} \ No newline at end of file diff --git a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/LinkedListTest.java b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/LinkedListTest.java similarity index 72% rename from group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/LinkedListTest.java rename to group24/315863321/src/test/java/com/johnChnia/coding2017/basic/LinkedListTest.java index bd8ad5ac4c..d09362cdf9 100644 --- a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/LinkedListTest.java +++ b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/LinkedListTest.java @@ -1,32 +1,31 @@ -package com.johnChnia.coding2017.basic.test; +package com.johnChnia.coding2017.basic; -import com.johnChnia.coding2017.basic.LinkedList; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.junit.MatcherAssert.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; /** * Created by john on 2017/3/9. */ public class LinkedListTest { - private LinkedList linkList1; - private LinkedList linkList2; - private LinkedList linkList3; - private LinkedList linkList4; - private LinkedList linkList5; - private LinkedList linkList6; + private LinkedList linkList1; + private LinkedList linkList2; + private LinkedList linkList3; + private LinkedList linkList4; + private LinkedList linkList5; + private LinkedList linkList6; @Before public void setUp() throws Exception { - linkList1 = new LinkedList(); - linkList2 = new LinkedList(); - linkList3 = new LinkedList(); - linkList4 = new LinkedList(); - linkList5 = new LinkedList(); - linkList6 = new LinkedList(); + linkList1 = new LinkedList<>(); + linkList2 = new LinkedList<>(); + linkList3 = new LinkedList<>(); + linkList4 = new LinkedList<>(); + linkList5 = new LinkedList<>(); + linkList6 = new LinkedList<>(); } @Test diff --git a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/QueueTest.java b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/QueueTest.java similarity index 82% rename from group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/QueueTest.java rename to group24/315863321/src/test/java/com/johnChnia/coding2017/basic/QueueTest.java index 54cd7f9385..191c6f568d 100644 --- a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/QueueTest.java +++ b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/QueueTest.java @@ -1,6 +1,5 @@ -package com.johnChnia.coding2017.basic.test; +package com.johnChnia.coding2017.basic; -import com.johnChnia.coding2017.basic.Queue; import org.junit.Before; import org.junit.Test; @@ -11,15 +10,15 @@ * Created by john on 2017/3/11. */ public class QueueTest { - Queue queue1; - Queue queue2; - Queue queue3; + Queue queue1; + Queue queue2; + Queue queue3; @Before public void setUp() throws Exception { - queue1 = new Queue(); - queue2 = new Queue(); - queue3 = new Queue(); + queue1 = new Queue<>(); + queue2 = new Queue<>(); + queue3 = new Queue<>(); } diff --git a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/StackTest.java b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/StackTest.java similarity index 75% rename from group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/StackTest.java rename to group24/315863321/src/test/java/com/johnChnia/coding2017/basic/StackTest.java index 7fb4a35757..9d84f7367a 100644 --- a/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/test/StackTest.java +++ b/group24/315863321/src/test/java/com/johnChnia/coding2017/basic/StackTest.java @@ -1,29 +1,28 @@ -package com.johnChnia.coding2017.basic.test; +package com.johnChnia.coding2017.basic; -import com.johnChnia.coding2017.basic.Stack; import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.junit.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; /** * Created by john on 2017/3/10. */ public class StackTest { - Stack stack1; - Stack stack2; - Stack stack3; - Stack stack4; + Stack stack1; + Stack stack2; + Stack stack3; + Stack stack4; @Before public void setUp() throws Exception { - stack1 = new Stack(); - stack2 = new Stack(); - stack3 = new Stack(); - stack4 = new Stack(); + stack1 = new Stack<>(); + stack2 = new Stack<>(); + stack3 = new Stack<>(); + stack4 = new Stack<>(); } @Test diff --git a/group24/330657387/.project b/group24/330657387/.project index fab8d7f04c..e929d098c9 100644 --- a/group24/330657387/.project +++ b/group24/330657387/.project @@ -1,6 +1,6 @@ - 2017Learning + 2017Learning_330657387 diff --git a/group24/330657387/src/com/coding/basic/ArrayList.java b/group24/330657387/src/com/coding/basic/ArrayList.java deleted file mode 100644 index 1728a28291..0000000000 --- a/group24/330657387/src/com/coding/basic/ArrayList.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.coding.basic; - -import java.util.Arrays; - -public class ArrayList implements List { - - private int size = 0; - - private Object[] elementData = new Object[10]; - - public void ensureCapacity(int input) { - if (input > elementData.length) { - growCapacity(); - } - } - - private void growCapacity(){ - elementData = Arrays.copyOf(elementData, size * 2); - } - - 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 ++; - } - - private void rangeCheck(int index){ - if (index > size || index < 0){ - throw new IndexOutOfBoundsException(); - } - } - - public Object get(int index){ - rangeCheck(index); - return elementData[index]; - } - - public Object remove(int index){ - rangeCheck(index); - Object dest = elementData[index]; - System.arraycopy(elementData, index +1, elementData, index, size-index-1); - size --; - return dest; - } - - public int size(){ - return size; - } - - public Iterator iterator(){ - return null; - } - -} diff --git a/group24/330657387/src/main/week01/data_structure/ArrayList.java b/group24/330657387/src/main/week01/data_structure/ArrayList.java new file mode 100644 index 0000000000..9a2f4d2c8b --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/ArrayList.java @@ -0,0 +1,88 @@ +package main.week01.data_structure; + +import java.util.Arrays; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[10]; + + private void ensureCapacity(int input) { + if (input > elementData.length) { + growCapacity(); + } + } + + private void growCapacity() { + elementData = Arrays.copyOf(elementData, size * 2); + } + + private void rangeCheck(int index) { + if (index > size || index < 0) { + throw new IndexOutOfBoundsException(); + } + } + + 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 dest = elementData[index]; + System.arraycopy(elementData, index + 1, elementData, index, size + - index - 1); + elementData[size---1]=null;//ֹڴй© + return dest; + } + + public int size() { + return size; + } + + public class ArrayListIterator implements Iterator { + + private ArrayList list; + + private int position = 0; + + private ArrayListIterator() { + } + + private ArrayListIterator(ArrayList list) { + this.list = list; + } + + @Override + public boolean hasNext() { + return position + 1 <= list.size; + } + + @Override + public Object next() { + return list.get(position++); + } + + } + + public ArrayListIterator iterator() { + return new ArrayListIterator(this); + } + +} diff --git a/group24/330657387/src/main/week01/data_structure/BinaryTreeNode.java b/group24/330657387/src/main/week01/data_structure/BinaryTreeNode.java new file mode 100644 index 0000000000..296744c188 --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/BinaryTreeNode.java @@ -0,0 +1,121 @@ +package main.week01.data_structure; + +import com.sun.org.apache.regexp.internal.recompile; + +public class BinaryTreeNode { + + private T data; + private BinaryTreeNode left; + private BinaryTreeNode right; + private int size; + + public BinaryTreeNode(){} + + public BinaryTreeNode(T data) + { + this.data=data; + this.left=null; + this.right=null; + } + + 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; + } + + /** + * dataظ + * @param data + * @return + */ + public BinaryTreeNode insert(T data){ + int compareResult = this.data.compareTo(data); + if(compareResult == 0){ + return this; + } + if(compareResult > 0){ + if(this.left == null){ + this.left = new BinaryTreeNode(data); + return this.left; + }else{ + return this.left.insert(data); + } + }else{ + if(this.right == null){ + this.right = new BinaryTreeNode(data); + return this.right; + }else{ + return this.right.insert(data); + } + } + } + + /** + * ڵΪ + * @param data + * @return + */ + @SuppressWarnings("unchecked") + public BinaryTreeNode search(T data){ + if(this.data == null){ + return null; + } + int compareResult = this.data.compareTo(data); + if (compareResult > 0) { + if (this.left == null) { + return null; + } else { + return this.left.search(data); + } + } else if (compareResult < 0) { + if (this.right == null) { + return null; + } else { + return this.right.search(data); + } + } else { + return this; + } + + } + + private BinaryTreeNode findMin() { + if (this.data == null) { + return null; + } + if (this.left == null) { + return this; + } + return this.left.findMin(); + } + + private BinaryTreeNode findMax() { + if (this.data == null) { + return null; + } + if (this.right == null) { + return this; + } + return this.right.findMin(); + } + +} diff --git a/group24/330657387/src/main/week01/data_structure/Iterator.java b/group24/330657387/src/main/week01/data_structure/Iterator.java new file mode 100644 index 0000000000..194891e56a --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/Iterator.java @@ -0,0 +1,7 @@ +package main.week01.data_structure; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group24/330657387/src/com/coding/basic/LinkedList.java b/group24/330657387/src/main/week01/data_structure/LinkedList.java similarity index 51% rename from group24/330657387/src/com/coding/basic/LinkedList.java rename to group24/330657387/src/main/week01/data_structure/LinkedList.java index 8357e13254..b61df9f254 100644 --- a/group24/330657387/src/com/coding/basic/LinkedList.java +++ b/group24/330657387/src/main/week01/data_structure/LinkedList.java @@ -1,4 +1,4 @@ -package com.coding.basic; +package main.week01.data_structure; import java.util.NoSuchElementException; @@ -9,13 +9,10 @@ public class LinkedList implements List { public void add(Object o) { if (isEmpty()) { - head = new Node(o); + addFirst(o); } else { - Node tail = (Node)get(size-1); - Node node = new Node(o); - tail.next = node; + addLast(o); } - size++; } public boolean isEmpty() { @@ -24,40 +21,55 @@ public boolean isEmpty() { public void add(int index, Object o) { rangeCheck(index); - if (index ==0) { - Node node = new Node(o); - node.next = head; - head = node; + if (index == 0) { + addFirst(o); + } else if (index == size) { + addLast(o); } else { - Node pre = (Node)get(index-1); + Node pre = getNode(index - 1); Node node = new Node(o); node.next = pre.next; pre.next = node; + size++; } } - - private void rangeCheck(int index){ - if (index >= size || index <0){ - throw new IndexOutOfBoundsException(); + + private void rangeCheck(int index) { + if (index >= size || index < 0) { + throw new IndexOutOfBoundsException(); } } - + public Object get(int index) { rangeCheck(index); Node dest = head; - for (int i = 0; i< index; i++){ + for (int i = 0; i < index; i++) { dest = dest.next; } return dest.data; } + public Node getNode(int index) { + rangeCheck(index); + Node dest = head; + for (int i = 0; i < index; i++) { + dest = dest.next; + } + return dest; + } + public Object remove(int index) { rangeCheck(index); - Node pre = (Node)get(index); + if (index == 0) { + return removeFirst(); + }else if(index == size){ + return removeLast(); + } + Node pre = getNode(index - 1); Node dest = pre.next; pre.next = dest.next; - size --; - return dest; + size--; + return dest.data; } public int size() { @@ -68,11 +80,11 @@ public void addFirst(Object o) { Node node = new Node(o); node.next = head; head = node; - size ++; + size++; } public void addLast(Object o) { - Node last = (Node)get(size-1); + Node last = getNode(size - 1); Node node = new Node(o); last.next = node; size++; @@ -83,32 +95,20 @@ public Object removeFirst() { throw new NoSuchElementException(); } Node newhead = head; + Node dest = head; head = head.next; - size --; - return newhead; + size--; + return dest.data; } public Object removeLast() { - if (head == null) { - throw new NoSuchElementException(); - } - if (head.next == null) { - Node tmp = head; - head = null; - size --; - return tmp; - } - Node newLastNode = (Node)get(size-2); + Node newLastNode = getNode(size - 2); Node oldLastNode = newLastNode.next; newLastNode.next = null; - size --; + size--; return oldLastNode; } - public Iterator iterator() { - return null; - } - private static class Node { Object data; Node next; @@ -119,4 +119,32 @@ private static class Node { } } + public class LinkedListIterator implements Iterator { + + private LinkedList list; + + private int position = 0; + + private LinkedListIterator() { + } + + private LinkedListIterator(LinkedList list) { + this.list = list; + } + + @Override + public boolean hasNext() { + return position + 1 <= list.size; + } + + @Override + public Object next() { + return list.get(position++); + } + + } + + public LinkedListIterator iterator() { + return new LinkedListIterator(this); + } } diff --git a/group24/330657387/src/main/week01/data_structure/List.java b/group24/330657387/src/main/week01/data_structure/List.java new file mode 100644 index 0000000000..6cbc15f8ab --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/List.java @@ -0,0 +1,10 @@ +package main.week01.data_structure; + +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/group24/330657387/src/main/week01/data_structure/Queue.java b/group24/330657387/src/main/week01/data_structure/Queue.java new file mode 100644 index 0000000000..7da6edf433 --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/Queue.java @@ -0,0 +1,23 @@ +package main.week01.data_structure; + +public class Queue { + + private LinkedList elementData; + private int size = 0; + + public void enQueue(Object o){ + elementData.add(size++,o); + } + + public Object deQueue(){ + return elementData.remove(size---1); + } + + public boolean isEmpty(){ + return size == 0; + } + + public int size(){ + return size; + } +} diff --git a/group24/330657387/src/main/week01/data_structure/Stack.java b/group24/330657387/src/main/week01/data_structure/Stack.java new file mode 100644 index 0000000000..5fc5410fde --- /dev/null +++ b/group24/330657387/src/main/week01/data_structure/Stack.java @@ -0,0 +1,28 @@ +package main.week01.data_structure; + +public class Stack { + private ArrayList elementData = new ArrayList(); + private int size = 0; + + public void push(Object o) { + elementData.add(size++,o); + } + + public Object pop() { + Object temp = elementData.get(size-1); + elementData.remove(size---1); + return temp; + } + + public Object peek() { + return elementData.get(size-1); + } + + public boolean isEmpty() { + return size == 0; + } + + public int size() { + return size; + } +} diff --git a/group24/330657387/src/main/week02/practice/ArrayUtil.java b/group24/330657387/src/main/week02/practice/ArrayUtil.java new file mode 100644 index 0000000000..3ab82a31e8 --- /dev/null +++ b/group24/330657387/src/main/week02/practice/ArrayUtil.java @@ -0,0 +1,115 @@ +package main.week02.practice; + +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.length <= 1) { + return; + } + int i = 0, j = origin.length - 1; + int temp; + while (j > i) { + origin[i] = origin[i] ^ origin[j]; + origin[j] = origin[i] ^ origin[j]; + origin[i] = origin[i] ^ origin[j]; + 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) { + int i = 0; + for (int j = 0; j < oldArray.length; j++) { + if (0 != oldArray[j]) { + oldArray[i++] = oldArray[j]; + } + } + int[] newArray = new int[i]; + System.arraycopy(oldArray, 0, newArray, 0,newArray.length); + 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) { + 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/group24/330657387/src/test/week01/data_structure/ArrayListTest.java b/group24/330657387/src/test/week01/data_structure/ArrayListTest.java new file mode 100644 index 0000000000..d9d63339b2 --- /dev/null +++ b/group24/330657387/src/test/week01/data_structure/ArrayListTest.java @@ -0,0 +1,84 @@ +package test.week01.data_structure; + +import static org.junit.Assert.*; +import main.week01.data_structure.ArrayList; +import main.week01.data_structure.ArrayList.ArrayListIterator; + +import org.junit.Before; +import org.junit.Test; + +public class ArrayListTest { + + public static ArrayList list; + + @Before + public void setUp() throws Exception { + list = new ArrayList(); + } + + @Test + public void testAddObject() { + list.add(1); + list.add(2); + list.add(2); + assertEquals(3,list.size()); + } + + @Test + public void testAddIntObject() { + list.add(0,1); + list.add(1,2); + list.add(2,2); + list.add(0,2); + assertEquals(2,list.get(0)); + try{ + list.add(-1 , "test"); + fail("-1 can't be index"); + list.add(1000, "test"); + fail("out of range"); + }catch (Exception e){ + + } + } + + @Test + public void testGet() { + list.add("songhao"); + assertEquals("songhao", list.get(0)); + } + + @Test + public void testRemove() { + list.add("songhao"); + assertEquals("songhao", list.remove(0)); + } + + @Test + public void testSize(){ + list.add(0,1); + list.add(1,2); + list.add(2,2); + list.add(0,2); + assertEquals(4,list.size()); + } + + @Test + public void testIterator() { + list.add(0,1); + list.add(1,2); + list.add(2,3); + list.add(0,4); + ArrayListIterator iter = list.iterator(); + assertTrue(iter.hasNext()); + assertEquals(4, iter.next()); + assertTrue(iter.hasNext()); + assertEquals(1, iter.next()); + assertTrue(iter.hasNext()); + assertEquals(2, iter.next()); + assertTrue(iter.hasNext()); + assertEquals(3, iter.next()); + assertFalse(iter.hasNext()); + + } + +} diff --git a/group24/330657387/src/test/week01/data_structure/BinaryTreeNodeTest.java b/group24/330657387/src/test/week01/data_structure/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..515da2e7d4 --- /dev/null +++ b/group24/330657387/src/test/week01/data_structure/BinaryTreeNodeTest.java @@ -0,0 +1,28 @@ +package test.week01.data_structure; + +import static org.junit.Assert.*; +import main.week01.data_structure.BinaryTreeNode; + +import org.junit.Before; +import org.junit.Test; + +public class BinaryTreeNodeTest { + + @Before + public void setUp() throws Exception { + } + + @Test + public void testInsert() { + BinaryTreeNode head=new BinaryTreeNode(); + + head.setData(5); + head.insert(2); + head.insert(7); + head.insert(1); + head.insert(4); + head.insert(3); + assertEquals(3,head.getLeft().getRight().getLeft().getData()); + } + +} diff --git a/group24/330657387/src/test/week01/data_structure/LinkedListTest.java b/group24/330657387/src/test/week01/data_structure/LinkedListTest.java new file mode 100644 index 0000000000..cf374a6dcb --- /dev/null +++ b/group24/330657387/src/test/week01/data_structure/LinkedListTest.java @@ -0,0 +1,54 @@ +package test.week01.data_structure; + +import static org.junit.Assert.*; +import main.week01.data_structure.LinkedList; +import main.week01.data_structure.LinkedList.LinkedListIterator; + +import org.junit.Before; +import org.junit.Test; + +public class LinkedListTest { + + private LinkedList list; + + @Before + public void setUp() throws Exception { + list = new LinkedList(); + } + + @Test + public void testGet() { + list.add("A"); + list.add("B"); + list.add(0, "C"); + assertEquals("C", list.get(0)); + } + + @Test + public void testRemove() { + list.add("A"); + list.add("B"); + list.add("C"); + list.add("D"); + list.add(0, "E"); + assertEquals("E", list.remove(0)); + assertEquals("D", list.remove(list.size()-1)); + assertEquals(3, list.size()); + } + + @Test + public void testIterator() { + LinkedListIterator iter = list.iterator(); + list.add("A"); + list.add("B"); + list.add(0, "C"); + assertTrue(iter.hasNext()); + assertEquals("C", iter.next()); + assertTrue(iter.hasNext()); + assertEquals("A", iter.next()); + assertTrue(iter.hasNext()); + assertEquals("B", iter.next()); + assertFalse(iter.hasNext()); + } + +} diff --git a/group24/330657387/src/test/week02/practice/ArrayUtilTest.java b/group24/330657387/src/test/week02/practice/ArrayUtilTest.java new file mode 100644 index 0000000000..1bf97fced3 --- /dev/null +++ b/group24/330657387/src/test/week02/practice/ArrayUtilTest.java @@ -0,0 +1,79 @@ +package test.week02.practice; + +import static org.junit.Assert.*; + +import java.util.Arrays; + +import main.week02.practice.ArrayUtil; + +import org.junit.Before; +import org.junit.Test; + + +public class ArrayUtilTest { + + ArrayUtil util; + + @Before + public void setUp() throws Exception { + util = new ArrayUtil(); + } + + @Test + public void testReverseArray() { + int[][] origin = {{1,20,5,3,65,4,6,9,7}, + {1}, + {1,2,3}, + {}, + {23,32}}; + for(int[] a : origin){ + System.out.println("前:"+Arrays.toString(a)); + util.reverseArray(a); + System.out.println("后:"+Arrays.toString(a)); + } + } + + @Test + public void testRemoveZero() { + int[][] origin = {{1,20,0,0,5,3,65,4,0,6,9,7}, + {1,0}, + {1,0,2,3,0}, + {}, + {23,0,0,32}}; + for(int[] a : origin){ + System.out.println("前:"+Arrays.toString(a)); + System.out.println("后:"+Arrays.toString(util.removeZero(a))); + } + } + + @Test + public void testMerge() { + fail("Not yet implemented"); + } + + @Test + public void testGrow() { + fail("Not yet implemented"); + } + + @Test + public void testFibonacci() { + fail("Not yet implemented"); + } + + @Test + public void testGetPrimes() { + fail("Not yet implemented"); + } + + @Test + public void testGetPerfectNumbers() { + fail("Not yet implemented"); + } + + @Test + public void testJoin() { + fail("Not yet implemented"); + } + +} diff --git a/group24/448641125/out/production/448641125/com/donaldy/litestruts/struts.xml b/group24/448641125/out/production/448641125/com/donaldy/litestruts/struts.xml new file mode 100644 index 0000000000..823895e9bc --- /dev/null +++ b/group24/448641125/out/production/448641125/com/donaldy/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/448641125/src/com/donaldy/basic/ArrayUtil.java b/group24/448641125/src/com/donaldy/basic/ArrayUtil.java new file mode 100644 index 0000000000..73f956258d --- /dev/null +++ b/group24/448641125/src/com/donaldy/basic/ArrayUtil.java @@ -0,0 +1,212 @@ +package com.donaldy.basic; + +import java.util.ArrayList; + +public class ArrayUtil { + + private java.util.ArrayList arrayList; + private int[] newArr; + /** + * 给定一个整形数组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){ + makeSure(origin); + /*int length = origin.length - 1; + int [] newArr = new int[length + 1]; + + for (int i = 0; i <= length; ++i) + newArr[i] = origin[length - i]; + + for (int i = 0 ; i <= length; ++i) + origin[i] = newArr[i];*/ + + for (int i = 0, j = origin.length - 1; i < j; ++i, --j) { + int t = origin[i]; + origin[i] = origin[j]; + origin[j] = t; + } + + } + + private void makeSure(int [] arr) { + if (arr.length == 0 || arr == null) + throw new RuntimeException(); + } + + /** + * 现在有如下的一个数组: 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){ + makeSure(oldArray); + int length = oldArray.length; + arrayList = new ArrayList(length); + for (int i = 0; i < length ; ++i) + if (oldArray[i] != 0) + arrayList.add(oldArray[i]); + + return toArray(arrayList.size()); + } + + private int[] toArray(int length) { + newArr = new int[length]; + for (int i = 0; i < length ; ++i) + newArr[i] = (int)arrayList.get(i); + 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){ + makeSure(array1); + makeSure(array2); + int length1 = array1.length; + int length2 = array2.length; + arrayList = new ArrayList(length1 + length2); + int i, j, cnt = 0, temp; + boolean flag = false; + for (i = 0, j = 0; i < length1 && j < length2; ) { + if (array1[i] < array2[j]) { + temp = array1[i]; + i ++; + } else { + temp = array2[j]; + j ++; + } + if (flag && temp != (int)arrayList.get(cnt)) { + arrayList.add(temp); + cnt ++; + } else if (!flag){ + arrayList.add(temp); + flag = true; + } + + } + for (i += 1; i < length1; ++i) + arrayList.add(array1[i]); + for (j += 1; j < length2; ++j) + arrayList.add(array2[j]); + + return toArray(arrayList.size()); + } + /** + * 把一个已经存满数据的数组 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 length = oldArray.length + size; + newArr = new int[length]; + int i = 0; + for (; i < oldArray.length ; ++i) + newArr[i] = oldArray[i]; + for (; i < length; ++i) + newArr[i] = 0; + 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) { + arrayList = new ArrayList(); + arrayList.add(1); + arrayList.add(1); + int maxn = 2; + int i = 1; + while (maxn < max) { + arrayList.add(maxn); + i ++; + maxn = (int)arrayList.get(i) + (int)arrayList.get(i - 1); + } + ; + return toArray(i + 1); + } + + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max) { + arrayList = new ArrayList(); + boolean prime[] = new boolean[max + 1]; + int p = 0; + for (int i = 0; i < max; ++i) + prime[i] = true; + prime[0] = prime[1] = false; + for (int i = 2; i < max; ++i) { + if (prime[i]) { + arrayList.add(p ++, i); + for (int j = 2 * i; j < max; j += i) + prime[j] = false; + } + } + return toArray(arrayList.size()); + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + arrayList = new ArrayList(); + int sum; + for (int i = 1; i < max; ++i) { + sum = 0; + for (int j = 1; j < i; ++j) { + if (i % j == 0) + sum += j; + } + if (sum == i) + arrayList.add(sum); + } + return toArray(arrayList.size()); + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param seperator + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(array[0]); + for (int i = 1; i < array.length; ++i) { + stringBuilder.append(seperator + array[i]); + } + return stringBuilder.toString(); + } + + +} diff --git a/group24/448641125/src/com/donaldy/download/DownloadThread.java b/group24/448641125/src/com/donaldy/download/DownloadThread.java new file mode 100644 index 0000000000..2d018cec3d --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/DownloadThread.java @@ -0,0 +1,45 @@ +package com.donaldy.download; + +import com.donaldy.download.api.Connection; + +import java.io.IOException; +import java.io.RandomAccessFile; + +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("running --"); + try ( + + RandomAccessFile raf = new RandomAccessFile("test.jpg", "rw") + + ) + { + raf.seek(startPos); + + byte [] buffer = conn.read(startPos, endPos); + + int hasRead = conn.getContentLength(); + + System.out.println("hasRead : " + hasRead); + + if (hasRead > 0) + raf.write(buffer, 0, hasRead); + + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("write part file default!"); + } + } +} diff --git a/group24/448641125/src/com/donaldy/download/FileDownloader.java b/group24/448641125/src/com/donaldy/download/FileDownloader.java new file mode 100644 index 0000000000..811d462be4 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/FileDownloader.java @@ -0,0 +1,93 @@ +package com.donaldy.download; + +import com.donaldy.download.api.Connection; +import com.donaldy.download.api.ConnectionException; +import com.donaldy.download.api.ConnectionManager; +import com.donaldy.download.api.DownloadListener; + +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute() throws IOException { + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (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; + + ExecutorService executorService = Executors.newFixedThreadPool(5); + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + int partLength = length ; + + System.out.println("partLengh : " + partLength); + + int startPos = 0; + + /*for (int i = 0 ; i < 5; ++ i) { + System.out.println("Thread is ready..."); + executorService.execute(new DownloadThread(conn, startPos, startPos + partLength)); + startPos += partLength; + }*/ + + new DownloadThread(conn, startPos, startPos + partLength).start(); + + executorService.shutdown(); + + Thread.sleep(10000); + + listener.notifyFinished(); + + } catch (ConnectionException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally{ + + } + } + + 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/group24/448641125/src/com/donaldy/download/FileDownloaderTest.java b/group24/448641125/src/com/donaldy/download/FileDownloaderTest.java new file mode 100644 index 0000000000..7cd0608bb6 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/FileDownloaderTest.java @@ -0,0 +1,57 @@ +package com.donaldy.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.donaldy.download.api.ConnectionManager; +import com.donaldy.download.api.DownloadListener; +import com.donaldy.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 Exception{ + + String url = "https://gss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/d1a20cf431adcbef25b551dfaaaf2edda2cc9f61.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/group24/448641125/src/com/donaldy/download/api/Connection.java b/group24/448641125/src/com/donaldy/download/api/Connection.java new file mode 100644 index 0000000000..bd5a61cdbc --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.donaldy.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/group24/448641125/src/com/donaldy/download/api/ConnectionException.java b/group24/448641125/src/com/donaldy/download/api/ConnectionException.java new file mode 100644 index 0000000000..f520af58cd --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.donaldy.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group24/448641125/src/com/donaldy/download/api/ConnectionManager.java b/group24/448641125/src/com/donaldy/download/api/ConnectionManager.java new file mode 100644 index 0000000000..318b031866 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/api/ConnectionManager.java @@ -0,0 +1,13 @@ +package com.donaldy.download.api; + +import java.io.IOException; +import java.net.MalformedURLException; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException, IOException; +} diff --git a/group24/448641125/src/com/donaldy/download/api/DownloadListener.java b/group24/448641125/src/com/donaldy/download/api/DownloadListener.java new file mode 100644 index 0000000000..af8e1e7d04 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.donaldy.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/group24/448641125/src/com/donaldy/download/impl/ConnectionImpl.java b/group24/448641125/src/com/donaldy/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..589a010e68 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/impl/ConnectionImpl.java @@ -0,0 +1,66 @@ +package com.donaldy.download.impl; + +import java.io.IOException; +import java.io.InputStream; + +import com.donaldy.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + int contentLength; + + InputStream inputStream; + + public void setContentLength(int contentLength) { + this.contentLength = contentLength; + } + + public void setInputStream (InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + if (inputStream == null) + return null; + + System.out.println("inputStream is not equal null"); + + inputStream.skip(startPos); + + int length = endPos - startPos + 1; + + System.out.println("要读的长度 : " + length); + + byte [] buffer = new byte[length]; + + System.out.println("buffer - 1: " + buffer.length); + + contentLength = inputStream.read(buffer); + + System.out.println("buffer - 2: " + buffer.length); + + System.out.println("contentLength : " + contentLength); + + return buffer; + } + + @Override + public int getContentLength() { + return contentLength; + } + + @Override + public void close() { + + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/group24/448641125/src/com/donaldy/download/impl/ConnectionImplTest.java b/group24/448641125/src/com/donaldy/download/impl/ConnectionImplTest.java new file mode 100644 index 0000000000..869b343787 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/impl/ConnectionImplTest.java @@ -0,0 +1,24 @@ +package com.donaldy.download.impl; + +import org.junit.Test; + +/** + * Created by donal on 2017/3/22. + */ +public class ConnectionImplTest { + + @Test + public void testRead() { + + } + + @Test + public void testGetContentLength() { + + } + + @Test + public void testClose() { + + } +} diff --git a/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImpl.java b/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..9c98b0d4fb --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,55 @@ +package com.donaldy.download.impl; + +import com.donaldy.download.api.Connection; +import com.donaldy.download.api.ConnectionException; +import com.donaldy.download.api.ConnectionManager; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + try { + URL urlName = new URL(url); + + HttpURLConnection connection = (HttpURLConnection) urlName.openConnection(); + + connection.setConnectTimeout(8000); + + connection.setRequestMethod("GET"); + + connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); + + connection.setRequestProperty("Accept", + "image/gif, image/jpeg, image/pjpeg, image/pjpeg, " + + "application/x-shockwave-flash, application/xaml+xml, " + + "application/vnd.ms-xpsdocument, application/x-ms-xbap, " + + "application/x-ms-application, application/vnd.ms-excel, " + + "application/vnd.ms-powerpoint, application/msword, */*"); + connection.setRequestProperty("Accept-Language", "zh-CN"); + + connection.setRequestProperty("Charset", "UTF-8"); + + ConnectionImpl conn = new ConnectionImpl(); + + conn.setContentLength(connection.getContentLength()); + + System.out.println("connection.getContentLength() : " + connection.getContentLength()); + + conn.setInputStream(connection.getInputStream()); + + return conn; + + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImplTest.java b/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImplTest.java new file mode 100644 index 0000000000..2ae3f8d3f8 --- /dev/null +++ b/group24/448641125/src/com/donaldy/download/impl/ConnectionManagerImplTest.java @@ -0,0 +1,19 @@ +package com.donaldy.download.impl; + +import org.junit.Test; + +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Created by donal on 2017/3/22. + */ +public class ConnectionManagerImplTest { + + @Test + public void testOpen() throws Exception{ + URL url = new URL(""); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + } +} diff --git a/group24/448641125/src/com/donaldy/litestruts/Configuration.java b/group24/448641125/src/com/donaldy/litestruts/Configuration.java new file mode 100644 index 0000000000..69415bf1fc --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/Configuration.java @@ -0,0 +1,116 @@ +package com.donaldy.litestruts; + +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.input.SAXBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by donal on 2017/3/21. + */ +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); + } + } + + 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); + + } + + + } + + public String getClassName(String action) { + ActionConfig ac = this.actions.get(action); + if(ac == null){ + return null; + } + return ac.getClassName(); + } + + public String getResultView(String action, String resultName) { + ActionConfig ac = this.actions.get(action); + if(ac == null){ + return null; + } + return ac.getViewName(resultName); + } + + //之所以为内部类,至少现在看来外界并不需要。 + 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/group24/448641125/src/com/donaldy/litestruts/ConfigurationException.java b/group24/448641125/src/com/donaldy/litestruts/ConfigurationException.java new file mode 100644 index 0000000000..fed8e00df5 --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/ConfigurationException.java @@ -0,0 +1,21 @@ +package com.donaldy.litestruts; + +import java.io.IOException; + +import org.jdom2.JDOMException; + +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/group24/448641125/src/com/donaldy/litestruts/ConfigurationTest.java b/group24/448641125/src/com/donaldy/litestruts/ConfigurationTest.java new file mode 100644 index 0000000000..4ef2386762 --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/ConfigurationTest.java @@ -0,0 +1,35 @@ +package com.donaldy.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Created by donal on 2017/3/21. + */ +public class ConfigurationTest { + + Configuration cfg = new Configuration("struts.xml"); + + @Test + public void testGetClassName() { + String clzName = cfg.getClassName("login"); + Assert.assertEquals("com.donaldy.litestruts.LoginAction", clzName); + clzName = cfg.getClassName("logout"); + Assert.assertEquals("com.donaldy.litestruts.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); + } +} diff --git a/group24/448641125/src/com/donaldy/litestruts/LoginAction.java b/group24/448641125/src/com/donaldy/litestruts/LoginAction.java new file mode 100644 index 0000000000..17d1842b09 --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/LoginAction.java @@ -0,0 +1,43 @@ +package com.donaldy.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public LoginAction() { + + } + + 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/group24/448641125/src/com/donaldy/litestruts/ReflectionUtiilTest.java b/group24/448641125/src/com/donaldy/litestruts/ReflectionUtiilTest.java new file mode 100644 index 0000000000..9c51567276 --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/ReflectionUtiilTest.java @@ -0,0 +1,99 @@ +package com.donaldy.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +/** + * Created by donal on 2017/3/21. + */ +public class ReflectionUtiilTest { + + @Test + public void testGetSetterMethod() throws Exception { + + String name = "com.coderising.litestruts.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 acctualNames = new HashSet<>(); + for(Method m : methods){ + acctualNames.add(m.getName()); + } + + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testSetParameters() throws Exception{ + + String name = "com.coderising.litestruts.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 = "com.coderising.litestruts.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 acctualNames = new HashSet<>(); + for(Method m : methods){ + acctualNames.add(m.getName()); + } + + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testGetParamters() throws Exception{ + String name = "com.donaldy.litestruts.LoginAction"; + Class clz = Class.forName(name); + LoginAction action = (LoginAction)clz.newInstance(); + action.setName("test"); + action.setPassword("123456"); + + + + + Map params = ReflectionUtil.getParamterMap(action); + + Assert.assertEquals(3, params.size()); + + Assert.assertEquals(null, params.get("messaage") ); + Assert.assertEquals("test", params.get("name") ); + Assert.assertEquals("123456", params.get("password") ); + } +} diff --git a/group24/448641125/src/com/donaldy/litestruts/ReflectionUtil.java b/group24/448641125/src/com/donaldy/litestruts/ReflectionUtil.java new file mode 100644 index 0000000000..764f1dd09f --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/ReflectionUtil.java @@ -0,0 +1,121 @@ +package com.donaldy.litestruts; + +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; + +/** + * Created by donal on 2017/3/21. + */ +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"); + } + + 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; + } + + public static Map getParamterMap(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; + } + + ////////////////////////Backup /////////////////////////////////// + + public static List getGetterMethods_V1(Class clz) { + + List methods = new ArrayList<>(); + + for(Method m : clz.getDeclaredMethods()){ + + if(m.getName().startsWith("get")){ + + methods.add(m); + + } + + } + + return methods; + } + + public static List getSetterMethods_V1(Class clz) { + + List methods = new ArrayList<>(); + + for(Method m : clz.getDeclaredMethods()){ + + if(m.getName().startsWith("set")){ + + methods.add(m); + + } + + } + + return methods; + + } +} diff --git a/group24/448641125/src/com/donaldy/litestruts/Struts.java b/group24/448641125/src/com/donaldy/litestruts/Struts.java new file mode 100644 index 0000000000..38d150ebb8 --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/Struts.java @@ -0,0 +1,185 @@ +package com.donaldy.litestruts; + +import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Pattern; + +public class Struts { + + + private final static Configuration cfg = new Configuration("struts.xml"); + + public static View runAction(String actionName, Map parameters) { + + 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.getParamterMap(action); + + View view = new View(); + view.setJsp(jsp); + view.setParameters(params); + + return view; + } 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; + } + + /*public static View runAction(String actionName, Map parameters) { + Element rootElement = null; + try { + *//** + * 0.读取配置文件 + *//* + rootElement = readStrutsXml().getRootElement(); + } catch (DocumentException e) { + e.printStackTrace(); + } + + *//** + * 1.根据actionName找到class + * 并设置 + *//* + String classPath = findClass(actionName, rootElement); + + return handle(classPath, parameters, rootElement); + } + + private static Document readStrutsXml() throws DocumentException { + SAXReader saxReader = new SAXReader(); + Document document = saxReader.read( + new File("D:\\tools\\Code\\Y_Repository\\coding2017\\group24\\448641125\\src\\com\\donaldy" + + "\\litestruts\\struts.xml")); + + return document; + } + + private static String findClass(String actionName, Element root) { + String classPath = null; + for (Iterator i = root.elementIterator(); i.hasNext(); ) { + Element action = (Element) i.next(); + if (actionName.equals(action.attribute("name").getText())) { + classPath = action.attribute("class").getText(); + break; + } + } + return classPath; + } + + private static View handle(String classPath, Map parameters + , Element rootElement) { + View view = new View(); + + Class newClass = getClass(classPath); + Object action = getObject(newClass); + Element element = rootElement.element("action"); + + + if (action instanceof LoginAction) { + LoginAction loginAction = (LoginAction) getAction(action, parameters); + String answer = loginAction.execute(); + String page = getPage(element, answer); + + view.setJsp(page); + view.setParameters(getMap(newClass, action)); + } + + return view; + } + + private static Class getClass(String classPath) { + try { + return Class.forName(classPath); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return null; + } + + private static Object getObject(Class newClass) { + try { + return newClass.newInstance(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + private static Object getAction(Object action, Map parameters) { + LoginAction loginAction = (LoginAction) action; + loginAction.setName(parameters.get("name")); + loginAction.setPassword(parameters.get("password")); + return loginAction; + } + + private static String getPage(Element element, String answer) { + for (Iterator i = element.elementIterator(); i.hasNext(); ) { + Element result = (Element) i.next(); + if (answer.equals(result.attribute("name").getText())) { + return result.getText(); + } + } + return ""; + } + + private static Map getMap(Class newClass, Object action) { + Map map = new HashMap<>(); + Method[] methods = newClass.getDeclaredMethods(); + String getterMethod; + for (Method method : methods) { + getterMethod = method.getName(); + if (Pattern.matches("get(\\w+)", getterMethod)) { + try { + map.put(getterMethod.substring(3).toLowerCase(), + method.invoke(action).toString()); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + + } + return map; + }*/ + +} diff --git a/group24/448641125/src/com/donaldy/litestruts/StrutsTest.java b/group24/448641125/src/com/donaldy/litestruts/StrutsTest.java new file mode 100644 index 0000000000..6e17b7483c --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/StrutsTest.java @@ -0,0 +1,39 @@ +package com.donaldy.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/group24/448641125/src/com/donaldy/litestruts/View.java b/group24/448641125/src/com/donaldy/litestruts/View.java new file mode 100644 index 0000000000..1676cf90da --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/View.java @@ -0,0 +1,24 @@ +package com.donaldy.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/group24/448641125/src/com/donaldy/litestruts/struts.xml b/group24/448641125/src/com/donaldy/litestruts/struts.xml new file mode 100644 index 0000000000..823895e9bc --- /dev/null +++ b/group24/448641125/src/com/donaldy/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/448641125/src/com/donaldy/test/ArrayUtilTest.java b/group24/448641125/src/com/donaldy/test/ArrayUtilTest.java new file mode 100644 index 0000000000..b457e108da --- /dev/null +++ b/group24/448641125/src/com/donaldy/test/ArrayUtilTest.java @@ -0,0 +1,92 @@ +package com.donaldy.test; + +import com.donaldy.basic.ArrayUtil; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +/** + * Created by donal on 2017/3/13. + */ +public class ArrayUtilTest { + + private ArrayUtil arrayUtil; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @Before + public void before() { + arrayUtil = new ArrayUtil(); + } + + @Test + public void testReverseArray() { + int []A = {7, 9, 30, 3}; + int []B = {7, 9, 30, 3, 4}; + arrayUtil.reverseArray(A); + assertArrayEquals(new int[] {3, 30, 9, 7}, A); + arrayUtil.reverseArray(B); + assertArrayEquals(new int[] {4, 3, 30 , 9, 7}, B); + } + + @Test + public void testRuntimeException() { + thrown.expect(RuntimeException.class); + arrayUtil.reverseArray(null); + } + + @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}; + assertArrayEquals(newArr, arrayUtil.removeZero(oldArr)); + } + + @Test + public void testMerge() { + int [] arr1 = {3, 5, 7, 8}; + int [] arr2 = {4, 5, 6, 7}; + int [] answer = new int[]{3,4,5,6,7,8}; + assertArrayEquals(answer, arrayUtil.merge(arr1, arr2)); + } + + @Test + public void testGrow() { + int [] oldArray = {2, 3, 6}; + int [] newArray = {2, 3, 6, 0, 0, 0}; + assertArrayEquals(newArray, arrayUtil.grow(oldArray, 3)); + } + + @Test + public void testFibonacci() { + int [] testArr = {1, 1, 2, 3, 5, 8, 13}; + int [] testArr2 = {1, 1}; + assertArrayEquals(testArr, arrayUtil.fibonacci(15)); + assertArrayEquals(testArr2, arrayUtil.fibonacci(2)); + } + + @Test + public void testGetPrimes() { + int [] testArr = {2, 3, 5, 7, 11, 13, 17, 19}; + assertArrayEquals(testArr, arrayUtil.getPrimes(23)); + } + + @Test + public void testGetPerfectNumbers() { + int [] testArr = {6}; + assertArrayEquals(testArr, arrayUtil.getPerfectNumbers(10)); + } + + @Test + public void testJoin() { + int [] testArr = {3, 8, 9}; + assertEquals("3-8-9", arrayUtil.join(testArr, "-")); + } +} diff --git a/group24/494800949/build.gradle b/group24/494800949/build.gradle index e88b275214..7930ebfca5 100644 --- a/group24/494800949/build.gradle +++ b/group24/494800949/build.gradle @@ -18,6 +18,8 @@ repositories { dependencies{ compile group: 'junit', name: 'junit', version: '4.11' + compile files("lib/dom4j-1.6.1.jar") + compile files("lib/jaxen-1.1.1.jar") } gradle.projectsEvaluated { tasks.withType(JavaCompile) { diff --git a/group24/494800949/src/main/java/com/coding/week2/array/ArrayUtil.java b/group24/494800949/src/main/java/com/coding/week2/array/ArrayUtil.java new file mode 100644 index 0000000000..f454b99d94 --- /dev/null +++ b/group24/494800949/src/main/java/com/coding/week2/array/ArrayUtil.java @@ -0,0 +1,217 @@ +package com.coding.week2.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 void reverseArray(int[] origin){ + int[] newArr = new int[origin.length]; + for(int i = origin.length - 1,j = 0; i >= 0; i--,j++){ + newArr[j] = origin[i]; + } + System.arraycopy(newArr, 0, origin, 0, origin.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[] newArr = new int[oldArray.length]; + int j = 0; + for(int i = 0; i < oldArray.length; i++){ + if(oldArray[i] != 0) + newArr[j++] = oldArray[i]; + } + int[] newArr1 = new int[j]; + System.arraycopy(newArr, 0, newArr1, 0, j); + return newArr1; + } + + /** + * 给定两个已经排序好的整形数组, 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 len = array1.length > array2.length ? array1.length : array2.length; + int[] newArr = new int[len]; + for(int i = 0; i < array1.length; i++){ + for(int j : array2){ + if(array1[i] == j){ + newArr[i] = array1[i]; + } + } + } + int[] newArr2 = new int[array1.length - newArr.length]; + for(int i = 0; i < array1.length; i++){ + for(int j : newArr){ + if(array1[i] == j) + continue; + } + } + int[] newArr1 = new int[array1.length + array2.length]; + System.arraycopy(array2, 0, newArr1, 0, array2.length); + System.arraycopy(newArr, 0, newArr1, array2.length-1, newArr.length); + bubuleSort(newArr1); + return newArr1; + } + + public void bubuleSort(int[] newArr1){ + for(int i = 0; i < newArr1.length; i++){ + for(int j = 0; j < newArr1.length; j++) + if(newArr1[i] < newArr1[j]){ + int temp = newArr1[i]; + newArr1[i] = newArr1[j] ; + newArr1[j] = temp; + } + } + } + /** + * 把一个已经存满数据的数组 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 < newArr.length; i++){ + if (i < oldArray.length){ + newArr[i] = oldArray[i]; + }else + newArr[i] = 0; + } + + 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){ + //1 得到小于max的斐波那契数 + //2 + + if( max == 1) + return new int[]{}; + int[] arr = new int[3]; + arr[0] = 1; + arr[1] = 1; + arr[2] = arr[0] + arr[1]; + if(max == 2) + return arr; + int i = 2; + while (max > arr[i]){ + if(i+1 >= arr.length){ + int capacity = arr.length + (arr.length >> 1); + int[] newArr = new int[capacity]; + System.arraycopy(arr, 0, newArr, 0, arr.length); + arr = newArr; + } + arr[++i] = arr[i - 1] + arr[i - 2]; + if(arr[i] < 0){ + System.out.println(Arrays.toString(arr)); + throw new OutOfMemoryError(); + } + } + + return removeZero(arr); + } + + + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max < 2) + return new int[]{}; + int[] arr = new int[max]; + for(int i = max; i >= 2; i--){ + if(isPrime(i)){ + arr[i] = i; + } + } + return removeZero(arr); + } + + private boolean isPrime(int value){ + for(int i = 2; i < Math.sqrt(value); i++){ + if(value % i == 0) + return false; + } + return true; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + int[] ints = new int[max+1]; + for(int i = 1; i <= max; i++){ + if(isPerfectNum(i)){ + ints[i] = i; + } + } + return removeZero(ints); + } + + + private boolean isPerfectNum(int value){ + if(value == 1) + return false; + int sum = 0; + for(int i = 1; i <= Math.sqrt(value); i++){ + if(value % i == 0){ + sum += i + value / i; + } + } + return sum-value == value; + } + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder builder = new StringBuilder(); + for(int i = 0; i < array.length; i++){ + builder.append(array[i]); + if(i != array.length - 1) + builder.append(seperator); + } + return builder.toString(); + } + + +} diff --git a/group24/494800949/src/main/java/com/coding/week2/litestruts/LoginAction.java b/group24/494800949/src/main/java/com/coding/week2/litestruts/LoginAction.java new file mode 100644 index 0000000000..1c90d49ccb --- /dev/null +++ b/group24/494800949/src/main/java/com/coding/week2/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coding.week2.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/group24/494800949/src/main/java/com/coding/week2/litestruts/Struts.java b/group24/494800949/src/main/java/com/coding/week2/litestruts/Struts.java new file mode 100644 index 0000000000..6448434800 --- /dev/null +++ b/group24/494800949/src/main/java/com/coding/week2/litestruts/Struts.java @@ -0,0 +1,121 @@ +package com.coding.week2.litestruts; + +import org.dom4j.DocumentException; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +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字段中。 + + */ + View view = new View(); + try { + //0 + //得到action类名 + String actionClassName = StrutsXmlUtil.getActionClassName(actionName); + + //得到action的结果及jsp路径 + Map jspMap = StrutsXmlUtil.getResultOfAction(actionName); + + //加载类 + Class clazz = Class.forName(actionClassName); + //实例化对象 + Object obj = clazz.newInstance(); + Method[] methods = clazz.getDeclaredMethods(); + + //1 注入action实例变量 + setFields(obj, methods, parameters); + + //2 执行action + String result = excute(obj, methods); + + + //3 获取返回的参数 + Map viewParams = buildReturnParams(obj, methods); + view.setParameters(viewParams); + + //4 设置返回的jsp + String jsp = jspMap.get(result); + view.setJsp(jsp); + + } catch (DocumentException | ClassNotFoundException + | InstantiationException | IllegalAccessException + | InvocationTargetException e) { + e.printStackTrace(); + } + return view; + } + + private static String excute(Object obj, Method[] methods ) + throws InvocationTargetException, IllegalAccessException { + for(Method method : methods){ + String methodName = method.getName(); + if("execute".equals(methodName)){ + return (String) method.invoke(obj); + } + } + return ""; + } + + + private static void setFields(Object obj, Method[] methods, Map parameters) + throws InvocationTargetException, IllegalAccessException { + Set> entities = parameters.entrySet(); + for(Map.Entry entry : entities){ + for(Method method : methods){ + if(method.getName().equals("set" + upperFirstChar(entry.getKey()))){ + method.invoke(obj, entry.getValue()); + } + } + } + } + + private static Map buildReturnParams(Object obj, Method[] methods) throws InvocationTargetException, IllegalAccessException { + Map viewParams = new HashMap<>(); + for(Method method : methods){ + String methodName = method.getName(); + if(methodName.startsWith("get")){ + Object ret = method.invoke(obj); + String field = methodName.substring(3); + viewParams.put(lowerFirstChar(field), ret); + } + } + return viewParams; + } + private static String upperFirstChar(String str){ + char[] cs = str.toCharArray(); + cs[0] -= 32; + return new String(cs); + } + + private static String lowerFirstChar(String str){ + char[] cs = str.toCharArray(); + cs[0] += 32; + return new String(cs); + } +} diff --git a/group24/494800949/src/main/java/com/coding/week2/litestruts/StrutsXmlUtil.java b/group24/494800949/src/main/java/com/coding/week2/litestruts/StrutsXmlUtil.java new file mode 100644 index 0000000000..e4cbee7480 --- /dev/null +++ b/group24/494800949/src/main/java/com/coding/week2/litestruts/StrutsXmlUtil.java @@ -0,0 +1,92 @@ +package com.coding.week2.litestruts; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.io.File; +import java.util.*; + +/** + * Created by Administrator on 2017/3/19 0019. + */ +public class StrutsXmlUtil { + + private static final String RESOURCE_PATH = "src/main/resources"; + private static final String STRUTS_CONFIG_FILE_NAME = "struts.xml"; + + private StrutsXmlUtil() { + } + + public static Document readXml(String path) throws DocumentException { + try { + SAXReader reader = new SAXReader(); + return reader.read(new File(path)); + } catch (DocumentException e) { + e.printStackTrace(); + throw e; + } + } + + + public static Iterator actionIterator(String path) throws DocumentException { + Document doc = readXml(path); + Element root = doc.getRootElement(); + return root.elementIterator("action"); + } + + public static String getActionClassName(String actionName) throws DocumentException { + Iterator iterator = actionIterator(getPathOfStrutsConfigurtion()); + if(actionName == null || "".equals(actionName)){ + throw new IllegalArgumentException("actionName can't be empty"); + } + while (iterator.hasNext()){ + Element e =(Element) iterator.next(); + if(actionName.equals(e.attributeValue("name"))){ + return e.attributeValue("class"); + } + } + return null; + } + + + public static String getPathOfStrutsConfigurtion(){ + File file = new File(RESOURCE_PATH); + List fileList = new ArrayList<>(); + + if (file.isDirectory()){ + File[] files = file.listFiles((dir, name) -> { + return name.equals(STRUTS_CONFIG_FILE_NAME); + }); + fileList.addAll(Arrays.asList(files)); + if(fileList.size() > 1){ + throw new RuntimeException("配置文件不止一个"); + }else if(fileList.size() == 0){ + throw new RuntimeException("找不到struts配置文件"); + } + } + return fileList.get(0).getPath(); + } + + public static Map getResultOfAction(String actionName) throws DocumentException { + Iterator iterator = actionIterator(getPathOfStrutsConfigurtion()); + Map res = new HashMap<>(); + while (iterator.hasNext()){ + Element e =(Element) iterator.next(); + System.out.println(e.getName()); + if(actionName.equals(e.attributeValue("name"))){ + Iterator resItr = e.elementIterator("result"); + while (resItr.hasNext()){ + Element result = (Element)resItr.next(); + System.out.println(result.attribute("name").getValue()); + System.out.println(result.getData()); + res.put(result.attribute("name").getValue(), result.getData().toString()); + } + + } + } + return res; + } + +} diff --git a/group24/494800949/src/main/java/com/coding/week2/litestruts/View.java b/group24/494800949/src/main/java/com/coding/week2/litestruts/View.java new file mode 100644 index 0000000000..bf7bd0d6c8 --- /dev/null +++ b/group24/494800949/src/main/java/com/coding/week2/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coding.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/group24/494800949/src/main/resources/struts.xml b/group24/494800949/src/main/resources/struts.xml new file mode 100644 index 0000000000..4133f6a2fb --- /dev/null +++ b/group24/494800949/src/main/resources/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/494800949/src/test/java/com/coding/week2/array/ArrayUtilTest.java b/group24/494800949/src/test/java/com/coding/week2/array/ArrayUtilTest.java new file mode 100644 index 0000000000..b402701691 --- /dev/null +++ b/group24/494800949/src/test/java/com/coding/week2/array/ArrayUtilTest.java @@ -0,0 +1,91 @@ +package com.coding.week2.array; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +/** + * Created by Administrator on 2017/3/19 0019. + */ +public class ArrayUtilTest { + + + private ArrayUtil arrayUtil; + + private int[] ints = new int[]{4, 9, 10, 3, 5, 0, 10, 12, 0, 9}; + + @Before + public void setup(){ + arrayUtil = new ArrayUtil(); + } + + @Test + public void testReverseArray() throws Exception { + arrayUtil.reverseArray(ints); + Assert.assertEquals(ints[0], 9); + Assert.assertEquals(ints[1], 0); + Assert.assertEquals(ints[2], 12); + Assert.assertEquals(ints[3], 10); + Assert.assertEquals(ints[4], 0); + } + + @Test + public void testRemoveZero() throws Exception { + int[] newInts = ints.clone(); + int[] newArr = arrayUtil.removeZero(newInts); + System.out.println(Arrays.toString(newArr)); + } + + @Test + public void testMerge() throws Exception { + int[] ints1 = new int[]{3, 4, 9, 20}; + int[] ints2 = new int[]{4, 6, 7, 12}; + int[] mergeArr = arrayUtil.merge(ints1, ints2); + System.out.println(Arrays.toString(mergeArr)); + } + + @Test + public void testGrow() throws Exception { + int[] newInts = arrayUtil.grow(ints, 5); + + Assert.assertEquals(newInts.length, 15); + Assert.assertEquals(newInts[14], 0); + Assert.assertEquals(newInts[13], 0); + Assert.assertEquals(newInts[12], 0); + Assert.assertEquals(newInts[11], 0); + Assert.assertEquals(newInts[10], 0); + } + + @Test + public void testFibonacci() throws Exception { + int[] ints = arrayUtil.fibonacci(100); + Assert.assertArrayEquals(ints, new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}); + } + + @Test + public void testGetPrimes() throws Exception { + int[] ints = arrayUtil.getPrimes(100); + System.out.println(Arrays.toString(arrayUtil.getPrimes(100))); + Assert.assertArrayEquals(ints, new int[]{2, 3, 4, 5, 7, 9, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}); + } + + @Test + public void testGetPerfectNumbers() throws Exception { + int[] ints = arrayUtil.getPerfectNumbers(10000); + long start = System.currentTimeMillis(); + System.out.println(Arrays.toString(arrayUtil.getPerfectNumbers(100000))); + long end = System.currentTimeMillis(); + System.out.println(end - start); + Assert.assertArrayEquals(ints, new int[]{6, 28, 496, 8128}); + } + + @Test + public void testJoin() throws Exception { + System.out.println(arrayUtil.join(ints, "|")); + Assert.assertEquals("4+9+10+3+5+0+10+12+0+9", arrayUtil.join(ints, "+")); + Assert.assertEquals("4|9|10|3|5|0|10|12|0|9", arrayUtil.join(ints, "|")); + } + +} \ No newline at end of file diff --git a/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsTest.java b/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsTest.java new file mode 100644 index 0000000000..bf16557d9c --- /dev/null +++ b/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsTest.java @@ -0,0 +1,36 @@ +package com.coding.week2.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +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/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsXmlUtilTest.java b/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsXmlUtilTest.java new file mode 100644 index 0000000000..bedff77fe6 --- /dev/null +++ b/group24/494800949/src/test/java/com/coding/week2/litestruts/StrutsXmlUtilTest.java @@ -0,0 +1,35 @@ +package com.coding.week2.litestruts; + +import org.dom4j.DocumentException; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Map; + +/** + * Created by Administrator on 2017/3/19 0019. + */ +public class StrutsXmlUtilTest { + + @Test + public void testGetClassNameOfAction() throws Exception { + String path = "src\\main\\java\\com\\coding\\week2\\litestruts\\struts.xml"; + + String actionCLass = StrutsXmlUtil.getActionClassName( "login"); + Assert.assertEquals(actionCLass, "com.coderising.litestruts.LoginAction"); + actionCLass = StrutsXmlUtil.getActionClassName("logout"); + Assert.assertEquals(actionCLass, "com.coderising.litestruts.LogoutAction"); + + } + + + @Test + public void testGetResultOfAction() throws DocumentException { + String path = "src\\main\\java\\com\\coding\\week2\\litestruts\\struts.xml"; + Map res = StrutsXmlUtil.getResultOfAction("login"); + Assert.assertNotNull(res.get("success"), "/jsp/homepage.jsp"); + Assert.assertNotNull(res.get("fail"), "/jsp/showLogin.jsp"); + } + + +} \ No newline at end of file diff --git a/group24/798277403/out/production/zhouliang/week2/litestruts/struts.xml b/group24/798277403/out/production/zhouliang/week2/litestruts/struts.xml new file mode 100644 index 0000000000..54550a4174 --- /dev/null +++ b/group24/798277403/out/production/zhouliang/week2/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/798277403/src/week2/array/ArrayUtil.java b/group24/798277403/src/week2/array/ArrayUtil.java new file mode 100644 index 0000000000..04c03f95e0 --- /dev/null +++ b/group24/798277403/src/week2/array/ArrayUtil.java @@ -0,0 +1,235 @@ +package week2.array; + +import java.util.Arrays; + + +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 原数组 + */ + void reverseArray(int[] origin){ + if(origin!=null && origin.length>0){ + int i, n; + for(i=0, n=origin.length-1; i0) { + int index = 0; + int length = 0; + int[] temp = new int[oldArray.length]; + for(int i=0; iarray2[j]){ + merges[index] = array2[j]; + j++; + }else{ + merges[index] = array2[j]; + i++; + j++; + split++; + } + } + while(i0) { + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < array.length; i++) { + stringBuffer.append(array[i]); + if (i != array.length - 1) { + stringBuffer.append(seperator); + } + } + return stringBuffer.toString(); + }else{ + return null; + } + } + +} diff --git a/group24/798277403/src/week2/array/ArrayUtilTest.java b/group24/798277403/src/week2/array/ArrayUtilTest.java new file mode 100644 index 0000000000..77c99242fa --- /dev/null +++ b/group24/798277403/src/week2/array/ArrayUtilTest.java @@ -0,0 +1,92 @@ +package week2.array; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Random; + +/** + * Created by zhouliang on 2017-03-13. + */ +public class ArrayUtilTest { + private int[] array; + private ArrayUtil arrayUtil ; + private int SIZE = 11; + + @Before + public void setUp() throws Exception { + arrayUtil = new ArrayUtil(); + array = new int[SIZE]; + Random random = new Random(); + + for(int i=0; i 配置,以及execute的返回值, 确定哪一个jsp, +放到View对象的jsp字段中。 + +*/ +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = null; + Class actionClass = null; + LoginAction loginAction = null; + View view = new View(); + try { + db = documentBuilderFactory.newDocumentBuilder(); + Document document = db.parse("src/week2/litestruts/struts.xml"); + NodeList nodeList = document.getElementsByTagName("action"); + + //遍历每一个action节点 + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + //获取action节点的所有属性集合 + NamedNodeMap attrs = node.getAttributes(); + //获取name结点的值 + String nodeName = attrs.getNamedItem("name").getNodeValue(); + + if(nodeName.equals(actionName)){ + //获取LoginAction实例 + actionClass = Class.forName(attrs.getNamedItem("class").getNodeValue()); + loginAction = (LoginAction) actionClass.newInstance(); + + //设置用户名密码属性 + Set> entrySet = parameters.entrySet(); + for (Map.Entry entry : entrySet) { + if (entry.getKey().equals("name")) { + loginAction.setName(entry.getValue()); + } + if (entry.getKey().equals("password")) { + loginAction.setPassword(entry.getValue()); + } + } + + //执行execute()方法 + String result = loginAction.execute(); + + //将message封装到view + String message = loginAction.getMessage(); + Map map = new HashMap(); + map.put("message",message); + view.setParameters(map); + + //解析对应的result节点 + NodeList childNodes = node.getChildNodes(); + //遍历childNodes获取每个节点的节点名和节点值 + for (int k = 0; k < childNodes.getLength(); k++) { + Node childNode = childNodes.item(k); + //区分出text类型的node以及element类型的node + if (childNode.getNodeType() == Node.ELEMENT_NODE) { + NamedNodeMap attributes = childNode.getAttributes(); + String nodeValue = attributes.getNamedItem("name").getNodeValue(); + if(nodeValue.equals(result)){ + view.setJsp(childNode.getTextContent()); + } + } + + } + + } + + } + } catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + + return view; + } + +/* DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = null; + Class actionClass = null; + LoginAction loginAction = null; + try { + db = documentBuilderFactory.newDocumentBuilder(); + Document document = db.parse("src/week2/litestruts/struts.xml"); + NodeList nodeList = document.getElementsByTagName("action"); + System.out.println("一共有" + nodeList.getLength() + "个结点"); + //遍历每一个action节点 + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + //获取action节点的所有属性集合 + NamedNodeMap attrs = node.getAttributes(); + //遍历action的属性 + for (int j = 0; j < attrs.getLength(); j++) { + //通过item(index)方法获取book节点的某一个属性 + Node attr = attrs.item(j); + String name = attrs.getNamedItem("name").getNodeValue(); + System.out.println("++++++++++"+name); + //获取属性名 + System.out.print("属性名:" + attr.getNodeName()); + //获取属性值 + System.out.println("--属性值" + attr.getNodeValue()); + if(attr.getNodeName().equals(actionName)){ + actionClass = Class.forName(attr.getNodeValue()); + loginAction = (LoginAction) actionClass.newInstance(); + } + } + //解析book节点的子节点 + NodeList childNodes = node.getChildNodes(); + //遍历childNodes获取每个节点的节点名和节点值 + for (int k = 0; k < childNodes.getLength(); k++) { + //区分出text类型的node以及element类型的node + if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) { + //获取了element类型节点的节点名 + System.out.print(childNodes.item(k).getNodeName()); + //获取了element类型节点的节点值 + System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue()); + System.out.println("--节点值是:" + childNodes.item(k).getTextContent()); + } + } + } + } catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + }*/ +} \ No newline at end of file diff --git a/group24/798277403/src/week2/litestruts/StrutsTest.java b/group24/798277403/src/week2/litestruts/StrutsTest.java new file mode 100644 index 0000000000..5c4379d912 --- /dev/null +++ b/group24/798277403/src/week2/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package week2.litestruts; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + + + + + +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/group24/798277403/src/week2/litestruts/View.java b/group24/798277403/src/week2/litestruts/View.java new file mode 100644 index 0000000000..01a422a808 --- /dev/null +++ b/group24/798277403/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/group24/798277403/src/week2/litestruts/struts.xml b/group24/798277403/src/week2/litestruts/struts.xml new file mode 100644 index 0000000000..54550a4174 --- /dev/null +++ b/group24/798277403/src/week2/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + diff --git a/group24/809203042/.classpath b/group24/809203042/.classpath new file mode 100644 index 0000000000..fb5011632c --- /dev/null +++ b/group24/809203042/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/group24/809203042/.gitignore b/group24/809203042/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/group24/809203042/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/group24/809203042/.project b/group24/809203042/.project new file mode 100644 index 0000000000..28fba6c7a5 --- /dev/null +++ b/group24/809203042/.project @@ -0,0 +1,17 @@ + + + 809203042Learning + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyArrayList.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyArrayList.java new file mode 100644 index 0000000000..b5157e1030 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyArrayList.java @@ -0,0 +1,101 @@ +package com.github.qq809203042.coding2017.basic.structures; + +import java.util.Arrays; + +/* + * 根据api中arraylist的方法描述,实现一个自己的arraylist + * 基于数组实现 + * + */ +public class MyArrayList implements MyList { + // 定义一个私有数组,初始长度为10 + private Object[] elementData = new Object[10]; + // 定义变量记录ArrayList的长度 + private int size = 0; + + // 获取指定索引上的元素的值 + @Override + public Object get(int index) { + if (index >= 0 && index < size) { + return elementData[index]; + } else { + throw new IndexOutOfBoundsException("查询的索引不存在"); + } + } +// 向列表尾部添加元素 + @Override + public boolean add(Object obj) { + if (size >= elementData.length) {// 若size大于等于现有数组长度,则将数组扩容后再进行操作 + elementData = Arrays.copyOf(elementData, elementData.length * 2); + } + elementData[size] = obj; + size++; + return true; +// 什么时候会返回false,如何返回false? + } +// 向列表指定位置添加元素 + @Override + public boolean add(Object obj,int index) { + if (size >= elementData.length) {// 若size大于等于现有数组长度,则将数组扩容后再进行操作 + elementData = Arrays.copyOf(elementData, elementData.length * 2); + } +// 将从index开始的所有元素向后移动一位 + moveBackward(elementData,index,size-1,1); +// 将元素添加到指定位置 + elementData[index] = obj; + size++; + return true; + } + +// 删除指定位置的元素 + @Override + public Object remove(int index) { + if(size == 0){ + throw new IndexOutOfBoundsException("列表为空"); + } + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("想要删除的元素索引不存在"); + } + Object removeElement = elementData[index]; + moveForward(elementData,index+1,size-1,1); +// 最后一位置为null;!! + elementData[size-1] = null; + size--; + return removeElement; + } + + @Override + public int size() { + + return size; + } +// 判断列表是否为空 + @Override + public boolean isEmpty() { + + return size == 0; + } +// 将数组从startPos位置到endPos位置的元素向后移动step步长 + private void moveBackward(Object[] elementData, int startPos, int endPos, int step) { + for(int i = endPos + step; i >= startPos + step; i--){ + elementData[i] = elementData[i-step]; + } + + } +// 将数组从startPos位置到endPos位置的元素向前移动step步长 + private void moveForward(Object[] elementData, int startPos, int endPos, int step) { + for(int i = startPos - step; i <= endPos - step; i++){ + elementData[i] = elementData[i+step]; + } + + } + @Override + public String toString() { +// return Arrays.toString(elementData); + Object[] myArrayList = Arrays.copyOf(elementData, size); + return Arrays.toString(myArrayList); + + } + + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyBinaryTree.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyBinaryTree.java new file mode 100644 index 0000000000..8d57321a1e --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyBinaryTree.java @@ -0,0 +1,156 @@ +package com.github.qq809203042.coding2017.basic.structures; + + +/* + * 实现二叉树, + * 只存储int类型 + * 内部类代表每个节点:每个节点含有一个键,一个值,一条左链接,一条右链接 + * + * 实现插入值操作:当root为空时插在root上:确定某一节点上是否为空 + * + */ +public class MyBinaryTree { + private BinaryTreeNode root ; + private int size; + +// 构造函数 + public MyBinaryTree(){ + + } + + public boolean getValue(Integer key){ + return getValue(root,key); + } + + private boolean getValue(BinaryTreeNode node,Integer key){ + if(node == null){//如果为空,则为空,没有该元素 + return false; + } + Integer value = node.getValue(); + if(value == key){//找到 + return true; + } + else if(value.compareTo(key) > 0){//如果小于该节点对象,比较左节点 + return getValue(node.left,key); + }else{ + return getValue(node.right,key);//如果小于该节点对象,比较右节点 + } + + } + + public void add(Integer key){ + root = add(root, key); + + } + + private BinaryTreeNode add(BinaryTreeNode node, Integer key) { + if(node == null){//若没有该节点,则创建并添加数据至节点中 + node = new BinaryTreeNode(key); + size++; + return node; + } + Integer value = node.getValue(); + if(value.compareTo(key) > 0){ + node.setLeft(add(node.left,key)); + + }else if(value.compareTo(key) < 0){ + node.setRight(add(node.right,key)); + + } + return node; + } + + public int size(){ + return size; + } + + +// 前序遍历 + public void preOrder(){ + preOrder(root); + System.out.println(); + } +// 中序遍历 + public void midOrder(){ + midOrder(root); + System.out.println(); + } +// 后序遍历 + public void aftOrder(){ + aftOrder(root); + System.out.println(); + } + +// 前序遍历 + private void preOrder(BinaryTreeNode node){ + if(node == null){ + return; + } + System.out.print(node.value + " "); + preOrder(node.left); + preOrder(node.right); + + } +// 中序遍历 + private void midOrder(BinaryTreeNode node){ + if(node == null){ + return; + } + midOrder(node.left); + System.out.print(node.value + " "); + midOrder(node.right); + + } +// 后序遍历 + private void aftOrder(BinaryTreeNode node){ + if(node == null){ + return; + } + aftOrder(node.left); + aftOrder(node.right); + System.out.print(node.value + " "); + + } + + + + // 二叉树的节点对象:每个节点含有一个键,一个值,一条左链接,一条右链接和一个节点计数器 + private static class BinaryTreeNode { + private Integer value; + + private BinaryTreeNode left; + private BinaryTreeNode right; +// 构造函数 + BinaryTreeNode(Integer value){ + this.value = value; + } + + + + public Integer getValue() { + return value; + } + public void setValue(Integer value) { + this.value = value; + } + + 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(Integer value) { + this.value = value; + return null; + } + + } +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyLinkedList.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyLinkedList.java new file mode 100644 index 0000000000..79f80df63e --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyLinkedList.java @@ -0,0 +1,172 @@ +package com.github.qq809203042.coding2017.basic.structures; + +/* + * 根据API实现自己的LinkedList数据结构 + */ +public class MyLinkedList implements MyList { + // 头节点对象,不存储元素,用于指示链表的起始位置 + private Node head = new Node(null,null); + // 尾节点对象 + private Node last = new Node(null,null); + // 链表长度 + int size = 0; + + @Override + public Object get(int index) { + Node node = node(index); + return node.data; + } + + @Override + public boolean add(Object obj) { + addLast(obj); + return true; + } + + @Override + public boolean add(Object obj, int index) { + if(index < 0 || index > size){ + throw new IndexOutOfBoundsException("下标越界"); + } + if(index == size){//等同于添加到末尾 + addLast(obj); + return true; + } + Node nodeIndex = node(index);//获取index处的节点 + Node newNode = new Node(obj,nodeIndex);//新增元素的next指向原来index处 + if(index == 0){ + head.next = newNode; + }else{ + Node nodeBeforeIndex = node(index-1); + nodeBeforeIndex.next = newNode; + } + size++; + return true; + } + + @Override + public Object remove(int index) { + if(index < 0 || index >= size){ + throw new IndexOutOfBoundsException("下标越界"); + } + if(index == 0){ + return removeFirst(); + }else{ + Node nodeIndex = node(index); + Object removeData = nodeIndex.data; + node(index-1).next = nodeIndex.next; + size--; + return removeData; + } + } + + @Override + public int size() { + + return size; + } + + @Override + public boolean isEmpty() { + + return size == 0; + } + + public void addFirst(Object obj) { + // 创建一个临时节点存储第一个节点 + Node tempFirst = head.next; + // 创建所需添加元素的节点对象 + Node newNode = new Node(obj, tempFirst); + head.next = newNode; + if (tempFirst == null) {// 如果链表中没有元素,则将添加的节点同时赋值为尾节点 + last = newNode; + } + size++; + } + + public void addLast(Object obj) { + // 创建一个临时节点存储尾节点 + Node tempLast = last; + // 创建所需添加元素的节点对象 + Node newNode = new Node(obj, null); + last = newNode; + if (size == 0) {// 如果链表中没有元素,则将添加的节点同时赋值为头节点 + head.next = newNode; + } else {// 如果链表中原先存在元素,则将原来尾节点的next指向现在的节点 + tempLast.next = newNode; + } + size++; + + } + + public Object removeFirst() { + if(size == 0){ + throw new NullPointerException("链表为空"); + } + Node removeNode =head.next; + Object removeData = removeNode.data; + head.next = removeNode.next; + size--; + return removeData; + } + + public Object removeLast() { + if(size <= 1){ + return removeFirst(); + }else{ + Object removeData = last.data; + last = node(size-2); + last.next = null; + size--; + return removeData; + } + } + + + + + @Override + public String toString() { + if(size == 0){ + return "[]"; + } + StringBuffer listToString = new StringBuffer(); + listToString.append("["); + Node node = head; + for(int i = 0; i < size;i++){ + node = node.next; + listToString.append(node.data); + if(i= size){ + throw new IndexOutOfBoundsException("下标越界"); + } + Node node = head.next; + for(int i = 1; i <= index; i++){ + node = node.next; + } + return node; + } +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyList.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyList.java new file mode 100644 index 0000000000..13bd0920c5 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyList.java @@ -0,0 +1,23 @@ +package com.github.qq809203042.coding2017.basic.structures; +/* + * 自定义list接口 + */ +public interface MyList { +// 查 + public abstract Object get(int index); + +// 增 + public abstract boolean add(Object obj); +// 在指定位置增 + public abstract boolean add(Object obj,int index); + +// 删除 + public abstract Object remove(int index); + +// 判断大小 + public abstract int size(); +// 判断是否为空 + public abstract boolean isEmpty(); + + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyQueue.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyQueue.java new file mode 100644 index 0000000000..cced80f1e8 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyQueue.java @@ -0,0 +1,30 @@ +package com.github.qq809203042.coding2017.basic.structures; + +import java.util.LinkedList; + +/* + * 实现队列的结构,使用链表结构 + */ +public class MyQueue { + private LinkedList queueList = new LinkedList<>(); + private int size; +// 进入队列 + public void enQueue(Object obj){ + queueList.addLast(obj); + size++; + } + + public Object deQueue(){ + Object removeElement = queueList.removeFirst(); + size--; + return removeElement; + } + + public boolean isEmpty(){ + return size == 0; + } + + public int size(){ + return size; + } +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyStack.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyStack.java new file mode 100644 index 0000000000..5657c91b50 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structures/MyStack.java @@ -0,0 +1,41 @@ +package com.github.qq809203042.coding2017.basic.structures; + +import java.util.ArrayList; + +public class MyStack { + private ArrayList elementData = new ArrayList(); +// 栈指针 + private int pos; +// 压栈 + public Object push(Object obj) { + elementData.add(obj); + pos++; + return obj; + } +// 弹栈 + public Object pop() { + if(isEmpty()){ + throw new StackOverflowError("栈溢出"); + } + return elementData.remove(--pos); + } +// 返回栈顶对象 + public Object peek() { + int topIndex = pos -1; + return elementData.get(topIndex); + } + + public boolean isEmpty() { + return pos == 0; + } + + public int size() { + return pos; + } + @Override + public String toString() { + return elementData.toString(); + } + + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyArrayListTest.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyArrayListTest.java new file mode 100644 index 0000000000..897fc596b2 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyArrayListTest.java @@ -0,0 +1,38 @@ +package com.github.qq809203042.coding2017.basic.structurestest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +import com.github.qq809203042.coding2017.basic.structures.MyArrayList; + + /* + * 用于测试MyArrayList + */ + +public class MyArrayListTest { + + public static void main(String[] args) { + + + MyArrayList mList = new MyArrayList(); + mList.add(new String("hahah")); + mList.add(new String("heihei")); + mList.add(new String("xixi")); + mList.add(new String("papapa")); + mList.add(new String("xiaoqiang")); + mList.add(new String("xiaoming")); + + System.out.println(mList); + System.out.println(mList.get(0)); + System.out.println(mList); + System.out.println(mList.add(new String("新元素"),3)); + System.out.println(mList); + System.out.println(mList.remove(0)); + System.out.println(mList); + System.out.println(mList.isEmpty()); + System.out.println(mList); + + System.out.println(mList.size()); + } + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyBinaryTreeTest.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyBinaryTreeTest.java new file mode 100644 index 0000000000..3e62719570 --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyBinaryTreeTest.java @@ -0,0 +1,23 @@ +package com.github.qq809203042.coding2017.basic.structurestest; + +import com.github.qq809203042.coding2017.basic.structures.MyBinaryTree; + +public class MyBinaryTreeTest { + + public static void main(String[] args) { + MyBinaryTree tree = new MyBinaryTree(); + tree.add(5); + tree.add(2); + tree.add(7); + tree.add(1); + tree.add(6); + tree.add(4); + tree.add(8); + + System.out.println(tree.size()); + tree.preOrder(); + tree.midOrder(); + tree.aftOrder(); + } + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyLinkedListTest.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyLinkedListTest.java new file mode 100644 index 0000000000..a13b940a3c --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyLinkedListTest.java @@ -0,0 +1,35 @@ +package com.github.qq809203042.coding2017.basic.structurestest; + +import com.github.qq809203042.coding2017.basic.structures.MyLinkedList; + +/* + * 用于测试MyLinkedList类 + */ +public class MyLinkedListTest { + + public static void main(String[] args) { + MyLinkedList mList = new MyLinkedList(); + System.out.println(mList.add(new String("hahah"))); + System.out.println(mList.add(new String("heihei"))); + System.out.println(mList.add(new String("xixi"))); + System.out.println(mList.add(new String("papapa"))); + System.out.println(mList.add(new String("xiaoqiang"))); + System.out.println(mList.add(new String("xiaoming"))); + + System.out.println(mList.size()); + System.out.println(mList); + System.out.println(mList.get(0)); + System.out.println(mList); + System.out.println(mList.add(new String("新元素"),0)); + mList.addFirst(new String("新元素2")); + mList.addLast(new String("新元素3")); + + System.out.println(mList.size()); + System.out.println(mList); + System.out.println(mList.remove(5)); + System.out.println(mList); + + System.out.println(mList.size()); + } + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyQueueTest.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyQueueTest.java new file mode 100644 index 0000000000..c9d25c9c4b --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyQueueTest.java @@ -0,0 +1,9 @@ +package com.github.qq809203042.coding2017.basic.structurestest; + +public class MyQueueTest { + + public static void main(String[] args) { + + } + +} diff --git a/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyStackTest.java b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyStackTest.java new file mode 100644 index 0000000000..cd32a0a50e --- /dev/null +++ b/group24/809203042/src/com/github/qq809203042/coding2017/basic/structurestest/MyStackTest.java @@ -0,0 +1,25 @@ +package com.github.qq809203042.coding2017.basic.structurestest; + +import com.github.qq809203042.coding2017.basic.structures.MyStack; + +public class MyStackTest { + + public static void main(String[] args) { + MyStack ms = new MyStack(); + ms.push(new String("yi")); + ms.push(new String("er")); + ms.push(new String("san")); + ms.push(new String("si")); + ms.push(new String("wu")); + ms.push(new String("liu")); + + System.out.println(ms); + ms.pop(); + System.out.println(ms); + ms.pop(); + System.out.println(ms); + System.out.println(ms.peek()); + System.out.println(ms.size()); + } + +} 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/group10/904627477/src/com/coding/BinaryTreeNode.java b/group26/1778842360/first heomework/src/BinaryTreeNode.java similarity index 91% rename from group10/904627477/src/com/coding/BinaryTreeNode.java rename to group26/1778842360/first heomework/src/BinaryTreeNode.java index fe50e3d1ae..b5e788838e 100644 --- a/group10/904627477/src/com/coding/BinaryTreeNode.java +++ b/group26/1778842360/first heomework/src/BinaryTreeNode.java @@ -1,32 +1,34 @@ -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/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/1252327158/task1_20170312/src/com/coding/ArrayList.java b/group27/1252327158/task1_20170312/src/com/coding/ArrayList.java index cce789d3b3..c3a4fc57d6 100644 --- a/group27/1252327158/task1_20170312/src/com/coding/ArrayList.java +++ b/group27/1252327158/task1_20170312/src/com/coding/ArrayList.java @@ -63,12 +63,12 @@ public T remove(int index){ if (index >= size || index < 0) { throw new IndexOutOfBoundsException(); } + modCount++; Object item = elementData[index]; for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i+1]; } - size--; - modCount++; + elementData[--size] = null; //清除该位置的引用,如果不赋null值,除非对应的位置被其他元素覆盖,否则原来的对象就一直不会被回收 return (T)item; } diff --git a/group27/1252327158/task1_20170312/.classpath b/group27/1252327158/task2_20170319/MyArrayUtils/.classpath similarity index 100% rename from group27/1252327158/task1_20170312/.classpath rename to group27/1252327158/task2_20170319/MyArrayUtils/.classpath diff --git a/group27/1252327158/task2_20170319/MyArrayUtils/.project b/group27/1252327158/task2_20170319/MyArrayUtils/.project new file mode 100644 index 0000000000..02a94adbf7 --- /dev/null +++ b/group27/1252327158/task2_20170319/MyArrayUtils/.project @@ -0,0 +1,17 @@ + + + MyArrayUtils + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtils.java b/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtils.java new file mode 100644 index 0000000000..2a4730cdc4 --- /dev/null +++ b/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtils.java @@ -0,0 +1,240 @@ +package com.coderising.array; + +import java.util.ArrayList; +import java.util.List; + +public class MyArrayUtils { + /** + * һ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){ + if (origin == null) { + return; + } + int temp = 0; + for (int i = 0; i < origin.length/2; i++) { + temp = origin[i]; + origin[i] = origin[origin.length - 1 - i]; + origin[origin.length - 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 static int[] removeZero(int[] oldArray){ + if (oldArray == null) { + return null; + } + int notZeroLength = oldArray.length; + for (int element : oldArray) { + if (element == 0) { + notZeroLength--; + } + } + if (notZeroLength == 0) { + return new int[0]; + } + int[] newArray = new int[notZeroLength]; + for (int i = 0,index = 0; i < oldArray.length; i++) { + if (oldArray[i] != 0) { + newArray[index++] = oldArray[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 static int[] merge(int[] array1, int[] array2){ + if (array1 == null && array2 == null) { + return null; + } + int[] newArray; + if (array1 == null) { + newArray = new int[array2.length]; + System.arraycopy(array2, 0, newArray, 0, array2.length); + return newArray; + } + if (array2 == null) { + newArray = new int[array1.length]; + System.arraycopy(array1, 0, newArray, 0, array1.length); + return newArray; + } + newArray = new int[array1.length + array2.length]; + int i = 0; + int j = 0; + int k = 0; + for (; i < array1.length && j < array2.length;) { + if (array1[i] < array2[j]) { + newArray[k++] = array1[i++]; + } else if (array1[i] == array2[j]) { + newArray[k++] = array1[i++]; + j++; + } else { + newArray[k++] = array2[j++]; + } + } + if (i == array1.length) { + System.arraycopy(array2, j, newArray, k, array2.length - j); + k += array2.length - j; + } + if (j == array2.length) { + System.arraycopy(array1, i, newArray, k, array1.length - i); + k += array1.length - i; + } + int[] results = new int[k]; + System.arraycopy(newArray, 0, results, 0, k); + return results; + } + /** + * һѾݵ 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){ + if (size <= 0 || oldArray == null) { + return oldArray; + } + int[] newArray = new int[oldArray.length + size]; + System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); + return newArray; + } + + /** + * 쳲Ϊ1123581321...... һֵ Сڸֵ + * 磬 max = 15 , 򷵻صӦΪ [11235813] + * max = 1, 򷵻ؿ [] + * @param max + * @return + */ + public static int[] fibonacci(int max){ + if (max <= 1) { + return new int[0]; + } + + List list = new ArrayList(); + int temp = 0; + for (int i = 0; ; i++) { + if ((temp = getfibonacci(i + 1)) < max) { + list.add(temp); + } else { + break; + } + } + + return List2Array(list); + } + + private static int getfibonacci(int i){ + if (i <= 2) { + return 1; + } + return getfibonacci(i-2) + getfibonacci(i-1); + } + + /** + * Сڸֵmax + * max = 23, صΪ[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public static int[] getPrimes(int max){ + if (max <= 2) { + return new int[0]; + } + List primeList = new ArrayList(); + primeList.add(2); + for (int i = 3; i < max; i += 2) { + int j; + for (j = 2; j <= Math.ceil(Math.sqrt(i)); j++) { + if (i % j == 0) { + break; + } + } + if (j == Math.ceil(Math.sqrt(i)) + 1) { + primeList.add(i); + } + } + + return List2Array(primeList); + } + + private static int[] List2Array(List list) { + int[] results = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + results[i] = list.get(i); + } + return results; + } + + /** + * ν ָǡõ֮ͣ6=1+2+3 + * һֵmax һ飬 Сmax + * @param max + * @return + */ + public static int[] getPerfectNumbers(int max){ + if (max < 2) { + return new int[0]; + } + List PerfectList = new ArrayList(); + for (int i = 1; i < max; i++) { + int factorSum = 0; + int j; + for ( j= 1; j < i; j++) { + if (i % j == 0) { + factorSum += j; + } + if (factorSum > i) { + break; + } + } + if (j == i && factorSum == i) { + PerfectList.add(i); + } + } + + return List2Array(PerfectList); + } + + /** + * seperator array + * array= [3,8,9], seperator = "-" + * 򷵻ֵΪ"3-8-9" + * @param array + * @param seperator + * @return + */ + public static String join(int[] array, String seperator){ + if (array == null || array.length < 1) { + return ""; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(array[0]); + for (int i = 1; i < array.length; i++) { + stringBuilder.append(seperator).append(array[i]); + } + return stringBuilder.toString(); + } +} diff --git a/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtilsTest.java b/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtilsTest.java new file mode 100644 index 0000000000..1b3f471e7f --- /dev/null +++ b/group27/1252327158/task2_20170319/MyArrayUtils/src/com/coderising/array/MyArrayUtilsTest.java @@ -0,0 +1,73 @@ +package com.coderising.array; + +import static org.junit.Assert.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class MyArrayUtilsTest { + + int[] myarray = {7, 9, 30, 3, 4}; + + @Before + public void setUp() throws Exception { + + } + + @Test + public void testReverseArray() { + int[] reverse = {4, 3, 30 , 9, 7}; + MyArrayUtils.reverseArray(myarray); + Assert.assertArrayEquals(reverse, myarray); + } + + @Test + public void testRemoveZero() { + int[] includeZero = {0, 3, 0 , 9, 0}; + int[] result = {3, 9}; + int[] excludeZero = MyArrayUtils.removeZero(includeZero); + Assert.assertArrayEquals(result, excludeZero); + + int[] allZero = {0, 0, 0, 0, 0}; + Assert.assertArrayEquals(new int[0], MyArrayUtils.removeZero(allZero)); + } + + @Test + public void testMerge() { + int[] a1 = {3, 5, 7,8,9,10}; + int[] a2 = {4, 5, 6,7}; + int[] a3 = {3,4,5,6,7,8,9,10}; + Assert.assertArrayEquals(a3, MyArrayUtils.merge(a1, a2)); + } + + @Test + public void testGrow() { + int[] newArray = {7, 9, 30, 3, 4, 0, 0, 0}; + Assert.assertArrayEquals(newArray, MyArrayUtils.grow(myarray, 3)); + } + + @Test + public void testFibonacci() { + int[] results = {1, 1, 2, 3, 5, 8, 13}; + Assert.assertArrayEquals(results, MyArrayUtils.fibonacci(15)); + } + + @Test + public void testGetPrimes() { + int[] results = {2,3,5,7,11,13,17,19}; + Assert.assertArrayEquals(results, MyArrayUtils.getPrimes(23)); + } + + @Test + public void testGetPerfectNumbers() { + int[] results = {6, 28, 496}; + Assert.assertArrayEquals(results, MyArrayUtils.getPerfectNumbers(500)); + } + + @Test + public void testJoin() { + Assert.assertEquals("7-9-30-3-4", MyArrayUtils.join(myarray, "-")); + } + +} diff --git a/group27/1252327158/task2_20170319/litestruts/.classpath b/group27/1252327158/task2_20170319/litestruts/.classpath new file mode 100644 index 0000000000..58abf08809 --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/group27/1252327158/task2_20170319/litestruts/.project b/group27/1252327158/task2_20170319/litestruts/.project new file mode 100644 index 0000000000..cc8facf311 --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/.project @@ -0,0 +1,17 @@ + + + litestruts + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group27/1252327158/task2_20170319/litestruts/.settings/org.eclipse.core.resources.prefs b/group27/1252327158/task2_20170319/litestruts/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000..10136c91b4 --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Fri Mar 17 10:33:43 CST 2017 +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/LoginAction.java b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/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/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/Struts.java b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..ce0ec1a04c --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/Struts.java @@ -0,0 +1,105 @@ +package com.coderising.litestruts; + +import java.io.File; +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.Map; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.*; + + +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字段中。 + + */ + + XMLHandle xmlHandle; + Class action = null; + Object object = null; + + try { + xmlHandle = new XMLHandle(); + String className = xmlHandle.getClassName(actionName); + if (className == null) { + return null; + } + action = Class.forName(className); + object = action.newInstance(); + Iterator> mapIt = parameters.entrySet().iterator(); + while (mapIt.hasNext()) { + Map.Entry entry = mapIt.next(); + Method[] methods = action.getDeclaredMethods(); + for (Method method : methods) { + if (method.getName().equalsIgnoreCase("set" + entry.getKey())) { + method.invoke(object, entry.getValue()); + } + } + } + + Method execute = action.getDeclaredMethod("execute"); + String result = (String)execute.invoke(object); + + Field[] fields = action.getDeclaredFields(); + Map map = new HashMap(); + for (Field field : fields) { + Method[] methods = action.getMethods(); + for (Method method : methods) { + if (method.getName().equalsIgnoreCase("get" + field.getName())) { + map.put(field.getName(), (String)method.invoke(object)); + } + } + } + View view = new View(); + view.setParameters(map); + String jspResult = xmlHandle.getResult(actionName, result); + view.setJsp(jspResult); + return view; + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + + return null; + } + +} diff --git a/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/StrutsTest.java b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/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/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/View.java b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/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/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/XMLHandle.java b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/XMLHandle.java new file mode 100644 index 0000000000..82a8073632 --- /dev/null +++ b/group27/1252327158/task2_20170319/litestruts/src/com/coderising/litestruts/XMLHandle.java @@ -0,0 +1,60 @@ +package com.coderising.litestruts; + +import java.io.File; +import java.util.Iterator; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +public class XMLHandle { + + private Document document = null; + + public XMLHandle() throws DocumentException { + SAXReader saxReader = new SAXReader(); + document = saxReader.read(new File("struts.xml")); + } + + private Element getElement(String actionName) { + Element root = document.getRootElement(); + Element result = null; + for (Iterator it = root.elementIterator(); it.hasNext();) { + Element element = it.next(); + if (element.attribute("name").getValue().equals(actionName)) { + //className = element.attribute("class").getValue(); + result = element; + break; + } + } + return result; + } + + public String getClassName(String actionName) { + String className = null; + Element element = getElement(actionName); + if (element != null) { + className = element.attribute("class").getValue(); + } + return className; + } + + public String getResult(String actionName, String resultName) { + String result = null; + Element element = getElement(actionName); + + if (element == null) { + return null; + } + for (Iterator it = element.elementIterator(); it.hasNext();) { + Element item = it.next(); + if (item.attribute("name").getValue().equals(resultName)) { + result = item.getText(); + break; + } + } + + return result; + } +} diff --git a/group27/1252327158/task2_20170319/litestruts/struts.xml b/group27/1252327158/task2_20170319/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/group27/1252327158/task2_20170319/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/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/group27/351592484/src/learn/Stack.java b/group27/351592484/src/learn/Stack.java new file mode 100644 index 0000000000..1fc79645f1 --- /dev/null +++ b/group27/351592484/src/learn/Stack.java @@ -0,0 +1,23 @@ +package com.liam.learn.code2017; + +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.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/liuxin/src/com/coderising/download/DownloadThread.java b/group27/513274874/homework/src/com/coding/coderising/download/DownloadThread.java similarity index 100% rename from liuxin/src/com/coderising/download/DownloadThread.java rename to group27/513274874/homework/src/com/coding/coderising/download/DownloadThread.java diff --git a/liuxin/src/com/coderising/download/FileDownloader.java b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloader.java similarity index 100% rename from liuxin/src/com/coderising/download/FileDownloader.java rename to group27/513274874/homework/src/com/coding/coderising/download/FileDownloader.java diff --git a/liuxin/src/com/coderising/download/FileDownloaderTest.java b/group27/513274874/homework/src/com/coding/coderising/download/FileDownloaderTest.java similarity index 100% rename from liuxin/src/com/coderising/download/FileDownloaderTest.java rename to group27/513274874/homework/src/com/coding/coderising/download/FileDownloaderTest.java 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/liuxin/src/com/coderising/download/impl/ConnectionImpl.java b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionImpl.java similarity index 100% rename from liuxin/src/com/coderising/download/impl/ConnectionImpl.java rename to group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionImpl.java diff --git a/liuxin/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionManagerImpl.java similarity index 100% rename from liuxin/src/com/coderising/download/impl/ConnectionManagerImpl.java rename to group27/513274874/homework/src/com/coding/coderising/download/impl/ConnectionManagerImpl.java 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/data-structure/src/com/coderising/download/DownloadThread.java b/liuxin/data-structure/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/liuxin/data-structure/src/com/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/liuxin/data-structure/src/com/coderising/download/FileDownloader.java b/liuxin/data-structure/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/liuxin/data-structure/src/com/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/liuxin/data-structure/src/com/coderising/download/FileDownloaderTest.java b/liuxin/data-structure/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/liuxin/data-structure/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://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/liuxin/data-structure/src/com/coderising/download/api/Connection.java b/liuxin/data-structure/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/download/api/ConnectionException.java b/liuxin/data-structure/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/liuxin/data-structure/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/liuxin/data-structure/src/com/coderising/download/api/ConnectionManager.java b/liuxin/data-structure/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/download/api/DownloadListener.java b/liuxin/data-structure/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/download/impl/ConnectionImpl.java b/liuxin/data-structure/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/liuxin/data-structure/src/com/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/liuxin/data-structure/src/com/coderising/download/impl/ConnectionManagerImpl.java b/liuxin/data-structure/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/liuxin/data-structure/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 null; + } + +} diff --git a/liuxin/data-structure/src/com/coderising/litestruts/LoginAction.java b/liuxin/data-structure/src/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/litestruts/Struts.java b/liuxin/data-structure/src/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/litestruts/StrutsTest.java b/liuxin/data-structure/src/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coderising/litestruts/View.java b/liuxin/data-structure/src/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/liuxin/data-structure/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/group11/1178243325/DataStructure/src/main/java/com/coding/basic/BinaryTreeNode.java b/liuxin/data-structure/src/com/coding/basic/BinaryTreeNode.java similarity index 88% rename from group11/1178243325/DataStructure/src/main/java/com/coding/basic/BinaryTreeNode.java rename to liuxin/data-structure/src/com/coding/basic/BinaryTreeNode.java index 1cf38aee30..d7ac820192 100644 --- a/group11/1178243325/DataStructure/src/main/java/com/coding/basic/BinaryTreeNode.java +++ b/liuxin/data-structure/src/com/coding/basic/BinaryTreeNode.java @@ -1,33 +1,32 @@ -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; - } - -} +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/liuxin/data-structure/src/com/coding/basic/Iterator.java b/liuxin/data-structure/src/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/data-structure/src/com/coding/basic/List.java b/liuxin/data-structure/src/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/liuxin/data-structure/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/liuxin/src/com/coding/basic/Queue.java b/liuxin/data-structure/src/com/coding/basic/Queue.java similarity index 92% rename from liuxin/src/com/coding/basic/Queue.java rename to liuxin/data-structure/src/com/coding/basic/Queue.java index 08d2d86b14..36e516e266 100644 --- a/liuxin/src/com/coding/basic/Queue.java +++ b/liuxin/data-structure/src/com/coding/basic/Queue.java @@ -1,19 +1,19 @@ -package com.coding.basic; - -public class Queue { - - public void enQueue(Object o){ - } - - public Object deQueue(){ - return null; - } - - public boolean isEmpty(){ - return false; - } - - public int size(){ - return -1; - } -} +package com.coding.basic; + +public class Queue { + + public void enQueue(Object o){ + } + + public Object deQueue(){ + return null; + } + + public boolean isEmpty(){ + return false; + } + + public int size(){ + return -1; + } +} diff --git a/group20/592146505/data _structure/src/org/wsc/stack/Stack.java b/liuxin/data-structure/src/com/coding/basic/Stack.java similarity index 80% rename from group20/592146505/data _structure/src/org/wsc/stack/Stack.java rename to liuxin/data-structure/src/com/coding/basic/Stack.java index 96b931ca07..459ec560b4 100644 --- a/group20/592146505/data _structure/src/org/wsc/stack/Stack.java +++ b/liuxin/data-structure/src/com/coding/basic/Stack.java @@ -1,6 +1,6 @@ -package org.wsc.stack; +package com.coding.basic; -import org.wsc.list.ArrayList; +import com.coding.basic.array.ArrayList; public class Stack { private ArrayList elementData = new ArrayList(); diff --git a/liuxin/src/com/coding/basic/ArrayList.java b/liuxin/data-structure/src/com/coding/basic/array/ArrayList.java similarity index 80% rename from liuxin/src/com/coding/basic/ArrayList.java rename to liuxin/data-structure/src/com/coding/basic/array/ArrayList.java index 57412dcf7f..4576c016af 100644 --- a/liuxin/src/com/coding/basic/ArrayList.java +++ b/liuxin/data-structure/src/com/coding/basic/array/ArrayList.java @@ -1,32 +1,35 @@ -package com.coding.basic; - -public class ArrayList implements List { - - private int size = 0; - - private Object[] elementData = new Object[100]; - - 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 Iterator iterator(){ - return null; - } - -} +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + 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 Iterator iterator(){ + return null; + } + +} diff --git a/liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java b/liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..45740e6d57 --- /dev/null +++ b/liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coding.basic.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/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrame.java b/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..a4f2c14606 --- /dev/null +++ b/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,60 @@ +package com.coding.basic.linklist; + +/** + * 用双向链表实现LRU算法 + * @author liuxin + * + */ +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + + } + + + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + +} diff --git a/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrameTest.java b/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..67cf36067b --- /dev/null +++ b/liuxin/data-structure/src/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,31 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + } + +} diff --git a/liuxin/src/com/coding/basic/LinkedList.java b/liuxin/data-structure/src/com/coding/basic/linklist/LinkedList.java similarity index 94% rename from liuxin/src/com/coding/basic/LinkedList.java rename to liuxin/data-structure/src/com/coding/basic/linklist/LinkedList.java index d162a3687c..f4c7556a2e 100644 --- a/liuxin/src/com/coding/basic/LinkedList.java +++ b/liuxin/data-structure/src/com/coding/basic/linklist/LinkedList.java @@ -1,122 +1,125 @@ -package com.coding.basic; - -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; - - } - - /** - * 把该链表逆置 - * 例如链表为 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){ - - } - /** - * 假定当前链表和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; - } -} +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +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; + + } + + /** + * 把该链表逆置 + * 例如链表为 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){ + + } + /** + * 假定当前链表和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; + } +} diff --git a/liuxin/mini-jvm/src/com/coderising/jvm/loader/ClassFileLoader.java b/liuxin/mini-jvm/src/com/coderising/jvm/loader/ClassFileLoader.java new file mode 100644 index 0000000000..86d4619407 --- /dev/null +++ b/liuxin/mini-jvm/src/com/coderising/jvm/loader/ClassFileLoader.java @@ -0,0 +1,34 @@ +package com.coderising.jvm.loader; + +import java.util.ArrayList; +import java.util.List; + + + +public class ClassFileLoader { + + private List clzPaths = new ArrayList(); + + public byte[] readBinaryCode(String className) { + + return null; + + + } + + + public void addClassPath(String path) { + + } + + + + public String getClassPath(){ + return null; + } + + + + + +} diff --git a/liuxin/mini-jvm/src/com/coderising/jvm/test/ClassFileloaderTest.java b/liuxin/mini-jvm/src/com/coderising/jvm/test/ClassFileloaderTest.java new file mode 100644 index 0000000000..a05534b210 --- /dev/null +++ b/liuxin/mini-jvm/src/com/coderising/jvm/test/ClassFileloaderTest.java @@ -0,0 +1,92 @@ +package com.coderising.jvm.test; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.jvm.loader.ClassFileLoader; + + + + + +public class ClassFileloaderTest { + + + static String path1 = "C:\\Users\\liuxin\\git\\coding2017\\liuxin\\mini-jvm\\bin"; + static String path2 = "C:\temp"; + + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testClassPath(){ + + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + loader.addClassPath(path2); + + String clzPath = loader.getClassPath(); + + Assert.assertEquals(path1+";"+path2,clzPath); + + } + + @Test + public void testClassFileLength() { + + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + + String className = "com.coderising.jvm.test.EmployeeV1"; + + byte[] byteCodes = loader.readBinaryCode(className); + + // 注意:这个字节数可能和你的JVM版本有关系, 你可以看看编译好的类到底有多大 + Assert.assertEquals(1056, byteCodes.length); + + } + + + @Test + public void testMagicNumber(){ + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + String className = "com.coderising.jvm.test.EmployeeV1"; + byte[] byteCodes = loader.readBinaryCode(className); + byte[] codes = new byte[]{byteCodes[0],byteCodes[1],byteCodes[2],byteCodes[3]}; + + + String acctualValue = this.byteToHexString(codes); + + Assert.assertEquals("cafebabe", acctualValue); + } + + + + + + + private String byteToHexString(byte[] codes ){ + StringBuffer buffer = new StringBuffer(); + for(int i=0;i