diff --git a/.gitignore b/.gitignore index 825a471a70..156b10d1f1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ + ################# ## Eclipse ################# @@ -258,24 +259,6 @@ tmp RemoteSystemsTempFiles .gitignore - -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 @@ -286,4 +269,3 @@ target *.DS_Store liuxin/.DS_Store liuxin/src/.DS_Store - 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/ArrayList.java similarity index 62% rename from group11/1310368322/GitHub/src/ArrayList.java rename to group11/1310368322/src/ArrayList.java index 68b42b1c03..b5024f1dfb 100644 --- a/group11/1310368322/GitHub/src/ArrayList.java +++ b/group11/1310368322/src/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/ArrayUtil.java b/group11/1310368322/src/ArrayUtil.java new file mode 100644 index 0000000000..81bc431679 --- /dev/null +++ b/group11/1310368322/src/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/Download/DownloadThread.java b/group11/1310368322/src/Download/DownloadThread.java new file mode 100644 index 0000000000..af248b72b2 --- /dev/null +++ b/group11/1310368322/src/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/Download/FileDownloader.java b/group11/1310368322/src/Download/FileDownloader.java new file mode 100644 index 0000000000..445ede2e3d --- /dev/null +++ b/group11/1310368322/src/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��ָ���� + // ��2��DownloadListener, �����Ƕ��߳����أ����������Ŀͻ��˲�֪��ʲôʱ���������������Ҫʵ�ֵ������̶߳�ִ�����Ժ󣬵���listener��notifiedFinished�����������ͻ��˾����յ�֪ͨ + // �����ʵ��˼·�� + // 1. ��Ҫ����ConnectionManager�� open ���������ӣ�Ȼ��ͨ�� Connection.getContentLength��������ļ��ij��� + // 2. ��������3���߳����أ�ע��ÿ���߳���Ҫ�ȵ���ConnectionManager��open���� + // Ȼ����� 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/Download/impl/ConnectionManagerImpl.java b/group11/1310368322/src/Download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..ff92aa77fe --- /dev/null +++ b/group11/1310368322/src/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/src/LinkedList.java b/group11/1310368322/src/LinkedList.java new file mode 100644 index 0000000000..488f2a22a6 --- /dev/null +++ b/group11/1310368322/src/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/test/ArrayUtilTest.java b/group11/1310368322/test/ArrayUtilTest.java new file mode 100644 index 0000000000..aaf3a80e7e --- /dev/null +++ b/group11/1310368322/test/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/FileDownloaderTest.java b/group11/1310368322/test/FileDownloaderTest.java new file mode 100644 index 0000000000..f337778812 --- /dev/null +++ b/group11/1310368322/test/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/283091182/src/com/coderising/download/DownloadThread.java b/group11/283091182/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..f8533373a4 --- /dev/null +++ b/group11/283091182/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,46 @@ +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; + String filePath = null; + private boolean finished = false; + + public boolean isFinished() { + return finished; + } + public DownloadThread( Connection conn, int startPos, int endPos,String filePath){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.filePath = filePath; + } + public void run(){ + File f = new File(this.filePath); + + try { + if(!f.exists()){ + f.createNewFile(); + } + RandomAccessFile raf = new RandomAccessFile(f, "rw"); + byte[] ba = conn.read(startPos, endPos); + System.out.println("["+this.getName()+"]ByteArray length="+ba.length+",endPos-startPos+1="+(endPos-startPos+1)); + raf.seek(startPos); + raf.write(ba, 0, endPos-startPos+1); + finished = true; + System.out.println("["+this.getName()+"]DownloadThread-startPos="+startPos+"-endPos="+endPos+":download completed"); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/group11/283091182/src/com/coderising/download/FileDownloader.java b/group11/283091182/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..0deb9a3cc4 --- /dev/null +++ b/group11/283091182/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,137 @@ +package com.coderising.download; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +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; + + private static int DOWNLOAD_SIZE_PER_THREAD = 1024*1000; + + private String destFilePath; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public FileDownloader(String _url,String destFilePath) { + this.url = _url; + this.destFilePath = destFilePath; + } + + 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(); + System.out.println("GetLength ="+length); + + File dest = new File(destFilePath); + dest.createNewFile(); + //fill the file with byte array to ensure the size +// byte[] ba = new byte[length]; +// FileOutputStream fos = new FileOutputStream(dest); +// fos.write(ba); +// fos.flush(); +// fos.close(); + + ArrayList threadPool = new ArrayList(); + int numOfThread = length/DOWNLOAD_SIZE_PER_THREAD; + if(length%DOWNLOAD_SIZE_PER_THREAD!=0) + { + numOfThread++; + } + + for(int i=0;ilength-1) + { + endPos = length-1; + } + DownloadThread t = new DownloadThread(cm.open(url),startPos,endPos,destFilePath); + t.setName("downloadThread_"+i); + System.out.println("Initializing Thread:"+t.getName()); + threadPool.add(t); + t.start(); + } + //pooling + boolean flag; + do{ + Iterator it = threadPool.iterator(); + flag=true; + DownloadThread t; + while(it.hasNext()){ + t = it.next(); + System.out.println("Thread ="+t.getName()+" has completed?"+t.isFinished()); + flag = flag && t.isFinished(); + } + if(!flag){ + System.out.println("=====================AllCompleted="+flag); + Thread.sleep(10*1000); + continue; + } + }while(!flag); + + } catch (Exception e) { + throw new RuntimeException("Error occured during download,",e); + }finally{ + if(conn != null){ + conn.close(); + } + } + getListener().notifyFinished(); + } + + 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/group11/283091182/src/com/coderising/download/FileDownloaderTest.java b/group11/283091182/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..583f3cb7d8 --- /dev/null +++ b/group11/283091182/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://download.theworld.cn/ver/TWInst_7.0.0.108.exe";//"http://src.onlinedown.net/Public/images/bigsoftimg/120000/q113222.jpg";// + String dest = "D:\\bt\\JavaDownload_TWInst_7.0.0.108.exe"; + FileDownloader downloader = new FileDownloader(url,dest); + + + 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/api/Connection.java b/group11/283091182/src/com/coderising/download/api/Connection.java similarity index 100% rename from liuxin/src/com/coderising/download/api/Connection.java rename to group11/283091182/src/com/coderising/download/api/Connection.java diff --git a/liuxin/src/com/coderising/download/api/ConnectionException.java b/group11/283091182/src/com/coderising/download/api/ConnectionException.java similarity index 100% rename from liuxin/src/com/coderising/download/api/ConnectionException.java rename to group11/283091182/src/com/coderising/download/api/ConnectionException.java diff --git a/liuxin/src/com/coderising/download/api/ConnectionManager.java b/group11/283091182/src/com/coderising/download/api/ConnectionManager.java similarity index 100% rename from liuxin/src/com/coderising/download/api/ConnectionManager.java rename to group11/283091182/src/com/coderising/download/api/ConnectionManager.java diff --git a/liuxin/src/com/coderising/download/api/DownloadListener.java b/group11/283091182/src/com/coderising/download/api/DownloadListener.java similarity index 100% rename from liuxin/src/com/coderising/download/api/DownloadListener.java rename to group11/283091182/src/com/coderising/download/api/DownloadListener.java diff --git a/group11/283091182/src/com/coderising/download/impl/ConnectionImpl.java b/group11/283091182/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..8750ac6b8d --- /dev/null +++ b/group11/283091182/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,74 @@ +package com.coderising.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + private URL url; + + private int length; + + private InputStream is; + + public ConnectionImpl(String url){ + try { + this.url = new URL(url); + this.length = getConnection(this.url).getContentLength(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Error opening connection.",e); + } + } + + private HttpURLConnection getConnection(URL url) throws MalformedURLException, IOException, ProtocolException { + HttpURLConnection conn = (HttpURLConnection)this.url.openConnection(); + conn.setRequestMethod("GET"); + conn.setConnectTimeout(30*1000); + return conn; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + byte[] buffer = new byte[1024]; + int tempLen = 0; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + HttpURLConnection conn = getConnection(url); + conn.setRequestProperty("Range", "bytes="+startPos+"-"+endPos); + this.is = conn.getInputStream(); + + while((tempLen = this.is.read(buffer))!=-1){ + baos.write(buffer, 0, tempLen); + } + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + return this.length; + } + + @Override + public void close() { + if(this.is!=null) + { + try { + this.is.close(); + this.url = null; + } catch (IOException e) { + // Safe to ignore + e.printStackTrace(); + } + + } + + } + +} diff --git a/group11/283091182/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group11/283091182/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..2d6768697e --- /dev/null +++ b/group11/283091182/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/group11/283091182/src/com/coding/basic2/Iterator.java b/group11/283091182/src/com/coding/basic2/Iterator.java new file mode 100644 index 0000000000..25895dc589 --- /dev/null +++ b/group11/283091182/src/com/coding/basic2/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic2; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/group11/283091182/src/com/coding/basic2/LinkedList.java b/group11/283091182/src/com/coding/basic2/LinkedList.java new file mode 100644 index 0000000000..4dd531e41b --- /dev/null +++ b/group11/283091182/src/com/coding/basic2/LinkedList.java @@ -0,0 +1,541 @@ +package com.coding.basic2; + +import static org.junit.Assert.assertEquals; + +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; + } + + } + + + 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()]; +//--Method One +// 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 + 4.0.0 + 2017Learning + 2017Learning + 0.0.1-SNAPSHOT + + src + + + src + + **/*.java + + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + com.google.guava + guava + 21.0 + + + \ No newline at end of file diff --git a/group11/395443277/src/com/coderising/download/DownloadThread.java b/group11/395443277/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..79be3a0c52 --- /dev/null +++ b/group11/395443277/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,47 @@ +package com.coderising.download; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread { + Connection conn; + int startPos; + int endPos; + String filePath; + CyclicBarrier barrier; + + 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 { + 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 new file mode 100644 index 0000000000..6d221f8c28 --- /dev/null +++ b/group11/395443277/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,103 @@ +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.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(String filePath) { + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (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 { + 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 / NUM_THREADS); + + // create a file + 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(); + } + } + + } + + 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; + } + + public void setConnectionManager(ConnectionManager ucm) { + this.cm = ucm; + } + + public DownloadListener getListener() { + return this.listener; + } + +} diff --git a/group11/395443277/src/com/coderising/download/FileDownloaderTest.java b/group11/395443277/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..152edbc664 --- /dev/null +++ b/group11/395443277/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 { + } + + @Test + 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 = "http://eskipaper.com/images/large-2.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + String filePath = "D://java_learning//test.jpg"; + downloader.execute(filePath); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/group11/395443277/src/com/coderising/download/api/Connection.java b/group11/395443277/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..5443fca61e --- /dev/null +++ b/group11/395443277/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/group11/395443277/src/com/coderising/download/api/ConnectionException.java b/group11/395443277/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/group11/395443277/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group11/395443277/src/com/coderising/download/api/ConnectionManager.java b/group11/395443277/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/group11/395443277/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/group11/395443277/src/com/coderising/download/api/DownloadListener.java b/group11/395443277/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/group11/395443277/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/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java b/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..c1de2c97b9 --- /dev/null +++ b/group11/395443277/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,75 @@ +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; + static final int BUFFER_SIZE = 1024; + + public ConnectionImpl(String url) { + try { + URL imgUrl = new URL(url); + urlcon = (HttpURLConnection) imgUrl.openConnection(); + } catch (Exception e) { + System.out.println(e); + } + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + 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(); + + while (baos.size() < totalLength) { + int len = is.read(buff); + if (len < 0) { + break; + } + baos.write(buff, 0, len); + } + + if (baos.size() > totalLength) { + byte[] data = baos.toByteArray(); + return Arrays.copyOf(data, totalLength); + } + + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + String contentLength = urlcon.getHeaderField("content-Length"); + + if (contentLength != null) { + return Integer.parseInt(contentLength); + } + + return 0; + } + + @Override + public void close() { + // try { + // is.close(); + // System.out.println("one connection is closed"); + // } catch (IOException e) { + // e.printStackTrace(); + // } + } + +} diff --git a/group11/395443277/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group11/395443277/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..21ae4b4f08 --- /dev/null +++ b/group11/395443277/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 { + Connection cn = new ConnectionImpl(url); + return cn; + } + +} diff --git a/group11/395443277/src/com/coderising/litestruts/struts.xml b/group11/395443277/src/com/coderising/litestruts/struts.xml index 7f8d558286..1b5028b0bd 100644 --- a/group11/395443277/src/com/coderising/litestruts/struts.xml +++ b/group11/395443277/src/com/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/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/LinkedList.java b/group11/395443277/src/com/coding/basic/LinkedList.java index fb9fbd81ca..df5d62aed8 100644 --- a/group11/395443277/src/com/coding/basic/LinkedList.java +++ b/group11/395443277/src/com/coding/basic/LinkedList.java @@ -3,84 +3,99 @@ import java.util.NoSuchElementException; public class LinkedList implements List { + private Node head; - - public void add(Object o){ + + public void add(Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = null; - + if (head == null) { head = newNode; } else { Node curr = head; - while(curr.next != null) { + while (curr.next != null) { curr = curr.next; } curr.next = newNode; } } - public void add(int index , Object o){ + + public void add(int index, Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = null; - + + if (index == 0) { + this.addFirst(o); + return; + } + if (head == null) { head = newNode; } else { Node curr = head; Node prev = curr; - while(index >0 && curr.next != null) { + while (index > 0 && curr.next != null) { prev = curr; curr = curr.next; index--; } - + prev.next = newNode; newNode.next = curr; } } - public Object get(int index){ + + public Object get(int index) { + if (index >= this.size()) { + return null; + } + Node curr = head; - while(index > 0) { + while (index > 0) { curr = curr.next; index--; - } + } return curr.data; } - public Object remove(int index){ - if (index ==0) { + + public Object remove(int index) { + if (index == 0) { return this.removeFirst(); } - + Node curr = head; Node prev = curr; - while(index >0 && curr.next != null) { + while (index > 0 && curr.next != null) { prev = curr; curr = curr.next; index--; } - + Object target = curr.data; prev.next = curr.next; curr.next = null; - + return target; } - public int size(){ + + public int size() { int size = 0; Node curr = head; - while(curr != null) { + while (curr != null) { size++; curr = curr.next; } return size; } - public void addFirst(Object o){ + + public void addFirst(Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = null; - + if (head == null) { head = newNode; } else { @@ -88,37 +103,40 @@ public void addFirst(Object o){ head.next = newNode; } } - public void addLast(Object o){ + + public void addLast(Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = null; - + Node curr = head; if (head == null) { head = newNode; } else { - while(curr.next != null) { + while (curr.next != null) { curr = curr.next; } curr.next = newNode; } } - public Object removeFirst(){ + + public Object removeFirst() { if (head == null) { return null; } - + Object target = head.data; head = head.next; return target; } - public Object removeLast(){ + + public Object removeLast() { if (head == null) { return null; } Node curr = head; Node prev = curr; - while(curr.next != null) { + while (curr.next != null) { prev = curr; curr = curr.next; } @@ -126,13 +144,23 @@ public Object removeLast(){ prev.next = null; return target; } - public Iterator iterator(){ + + public void print() { + Node curr = head; + + while (curr != null) { + System.out.println(curr.data); + curr = curr.next; + } + } + + public Iterator iterator() { return new SeqIterator(); } - + private class SeqIterator implements Iterator { Node curr = head; - + @Override public boolean hasNext() { return curr != null; @@ -140,17 +168,262 @@ public boolean hasNext() { @Override public Object next() { - if (!hasNext()) throw new NoSuchElementException(); + if (!hasNext()) + throw new NoSuchElementException(); Object target = curr.data; curr = curr.next; return target; } } - - private static class Node{ + + private static class Node { Object data; Node next; - + } + + /** + * 把该链表逆置 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + if (head != null) { + Node curr = head; + Node nextNode = null; + Node prev = null; + + // move curr node link + while (curr != null) { + // move link + nextNode = curr.next; + curr.next = prev; + + // move forward + prev = curr; + curr = nextNode; + } + + head = prev; + } + } + + /** + * 删除一个单链表的前半部分 例如:list = 2->5->7->8 , 删除以后的值为 7->8 如果list = 2->5->7->8->10 + * ,删除以后的值为7,8,10 + * + */ + public void removeFirstHalf() { + if (head != null) { + int listSize = this.size(); + int half = (int) Math.ceil(listSize / 2); + + Node curr = head; + while (half > 0) { + curr = curr.next; + head = curr; + half--; + } + } + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + if (head == null) { + return; + } + + if (i < 0) { + return; + } + + if (i > this.size() - 1) { + return; + } + + Node curr = head; + Node prev = head; + // move to index i + while (i > 0 && curr != null) { + prev = curr; + curr = curr.next; + i--; + } + + // if curr is out of bound return + if (curr == null) { + return; + } + + // else move length + while (length > 0 && curr != null) { + curr = curr.next; + length--; + } + + // special case to head + if (prev == head) { + head = curr; + } else { + prev.next = curr; + } + } + + /** + * 假定当前链表和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 null; + } + + if (head == null) { + return null; + } + + // TODO: remove list which not existed in the original list + // special case: 1->3->4->20 + + int[] newArr = new int[list.size()]; + int i = 0; + Iterator it = list.iterator(); + while (it.hasNext()) { + int id = (int) it.next(); + + // if element is not existed + if (this.get(id) != null) { + int listElement = (int) this.get(id); + newArr[i] = listElement; + i++; + } + } + + return newArr; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 从当前链表中中删除在list中出现的元素 + * + * @param list + */ + + public void subtract(LinkedList list) { + if (list.size() == 0) { + return; + } + + if (head == null) { + return; + } + + Iterator it = list.iterator(); + while (it.hasNext()) { + int id = (int) it.next(); + this.remove(id); + } + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + if (head == null) { + return; + } + + Node curr = head; + + // note: + // duplicate value in the first or last + // all values the same + while (curr.next != null) { + if (curr.data.equals(curr.next.data)) { + curr.next = curr.next.next; + } else { + curr = curr.next; + } + } + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + if (head == null) { + return; + } + + if (min > max) { + return; + } + + // only works for integer + Node curr = head; + Node prev = head; + // include last node + while (curr != null) { + if ((int) curr.data > min && (int) curr.data < max) { + // special case for head + if (curr == head) { + head = curr.next; + } else { + prev.next = curr.next; + curr = curr.next; + } + } else { + prev = curr; + curr = curr.next; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) { + if (list.size() == 0) { + return null; + } + + if (head == null) { + return null; + } + + // find size + int l1Size = this.size(); + int l2Size = list.size(); + + // runner + int i = 0; + int j = 0; + + LinkedList rtnList = new LinkedList(); + + while (i < l1Size && j < l2Size) { + if (this.get(i).equals(list.get(j))) { + rtnList.add(this.get(i)); + i++; + j++; + } else if ((int) this.get(i) < (int) list.get(j)) { + i++; + } else { + j++; + } + } + + return rtnList; } } diff --git a/group11/395443277/src/com/coding/basic/LinkedListTest.java b/group11/395443277/src/com/coding/basic/LinkedListTest.java index af5aa2d3a2..47418e188d 100644 --- a/group11/395443277/src/com/coding/basic/LinkedListTest.java +++ b/group11/395443277/src/com/coding/basic/LinkedListTest.java @@ -1,6 +1,7 @@ package com.coding.basic; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import org.junit.Test; @@ -124,4 +125,185 @@ public void testIterator() { assertEquals(3, it.next()); assertEquals(2, it.next()); } + + @Test + public void testReverse() { + LinkedList list = new LinkedList(); + list.add(3); + list.add(7); + list.add(10); + list.add(15); + + list.reverse(); + assertEquals(15, list.get(0)); + + LinkedList list2 = new LinkedList(); + list2.reverse(); + } + + @Test + public void testRemoveFirstHalf() { + LinkedList list = new LinkedList(); + list.add(2); + list.add(5); + list.add(7); + list.add(8); + list.add(10); + + list.removeFirstHalf(); + } + + + @Test + public void testRemoveDuplicateValues() { + LinkedList list = new LinkedList(); + list.add(1); + + // with single element + assertEquals(1, list.get(0)); + + // add another one with 1->1 + list.add(1); + list.removeDuplicateValues(); + assertEquals(1, list.get(0)); + assertEquals(1, list.size()); + + // test the duplicate value is the last one + for(int i=2; i<6; i++) { + list.add(i); + } + list.add(5); + list.removeDuplicateValues(); + assertEquals(5, list.get(4)); + assertEquals(5, list.size()); + + // regular + for(int i=0; i<6; i++) { + list.add(5); + } + list.add(6); + + list.removeDuplicateValues(); + assertEquals(6, list.get(5)); + assertEquals(6, list.size()); + } + + @Test + public void testRemoveRange() { + LinkedList list = new LinkedList(); + + // regular + for(int i=1; i<7; i++) { + list.add(i); + } + + list.removeRange(2, 4); + assertEquals(5, list.size()); + + // head case + list.add(1, 1); + list.removeRange(0, 3); + assertEquals(3, list.size()); + + // tail case + list.add(6); + list.add(7); + list.removeRange(5, 20); + assertEquals(2, list.size()); + } + + @Test + public void testRemoveLength() { + LinkedList list = new LinkedList(); + + // regular + for(int i=0; i<9; i++) { + list.add(i); + } + + // regular + list.remove(4, 2); + + // head + LinkedList list2 = new LinkedList(); + for(int i=0; i<9; i++) { + list2.add(i); + } + list2.remove(0, 3); + + // tail + LinkedList list3 = new LinkedList(); + for(int i=0; i<10; i++) { + list3.add(i); + } + list3.remove(9, 3); + assertEquals(9, list3.size()); + } + + @Test + public void testGetElements() { + LinkedList list1 = new LinkedList(); + // 11->101->201->301->401->501->601->701 + list1.add(11); + list1.add(101); + list1.add(201); + list1.add(301); + list1.add(401); + list1.add(501); + list1.add(601); + list1.add(701); + + LinkedList list2 = new LinkedList(); + // 1->3->4->6 + list2.add(1); + list2.add(3); + list2.add(4); + list2.add(6); + + int[] newArr = list1.getElements(list2); + assertArrayEquals(new int[]{101,301,401,601}, newArr); + } + + @Test + public void testSubtract() { + LinkedList list1 = new LinkedList(); + // 11->101->201->301->401->501->601->701 + list1.add(11); + list1.add(101); + list1.add(201); + list1.add(301); + list1.add(401); + list1.add(501); + list1.add(601); + list1.add(701); + + LinkedList list2 = new LinkedList(); + // 1->3->4->6 + list2.add(1); + list2.add(3); + list2.add(4); + list2.add(6); + + list1.subtract(list2); + // 11->201->501->701 + assertEquals(4, list1.size()); + } + + @Test + public void testIntersection() { + LinkedList list1 = new LinkedList(); + list1.add(1); + list1.add(2); + list1.add(4); + list1.add(5); + + LinkedList list2 = new LinkedList(); + list2.add(2); + list2.add(3); + list2.add(4); + list2.add(7); + + LinkedList l3 = list1.intersection(list2); + assertEquals(2, l3.size()); + } } 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/group11/501294009/JavaProject/module1/README.md b/group11/501294009/JavaProject/module1/README.md new file mode 100644 index 0000000000..933a3ef67e --- /dev/null +++ b/group11/501294009/JavaProject/module1/README.md @@ -0,0 +1 @@ +module1 is achieve ArrayList, LinkedList, Queue, Stack BinaryTree 和Iterator \ No newline at end of file diff --git a/group11/501294009/JavaProject/module1/pom.xml b/group11/501294009/JavaProject/module1/pom.xml new file mode 100644 index 0000000000..98bfd43a2c --- /dev/null +++ b/group11/501294009/JavaProject/module1/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + + com.yang + module1 + 1.0-SNAPSHOT + jar + + module1 + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + diff --git a/group11/501294009/JavaProject/module2/README.md b/group11/501294009/JavaProject/module2/README.md new file mode 100644 index 0000000000..9bf528719a --- /dev/null +++ b/group11/501294009/JavaProject/module2/README.md @@ -0,0 +1,15 @@ +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字段中。 diff --git a/group11/501294009/JavaProject/module2/pom.xml b/group11/501294009/JavaProject/module2/pom.xml new file mode 100644 index 0000000000..aee6c06186 --- /dev/null +++ b/group11/501294009/JavaProject/module2/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + com.yang + module2 + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + jar + + module2 + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + junit + junit + RELEASE + + + junit + junit + RELEASE + + + diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/LoginAction.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/LoginAction.java new file mode 100644 index 0000000000..377ae9c629 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/LoginAction.java @@ -0,0 +1,39 @@ +package com.yang; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @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/group11/501294009/JavaProject/module2/src/main/java/com/yang/Struts.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/Struts.java new file mode 100644 index 0000000000..c28148d584 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/Struts.java @@ -0,0 +1,124 @@ +package com.yang; + +import com.yang.bean.Action; +import com.yang.bean.Result; +import org.junit.Test; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +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 View view; + + public static View runAction(String actionName, Map parameters) { + view = null; + + try { + com.yang.bean.Struts struts = (com.yang.bean.Struts) getBean(com.yang.bean.Struts.class, "struts.xml"); + + List actions = struts.getActions(); + actions.forEach((Action action) -> { + try { + renderView(actionName, parameters, action); + } catch (Exception e) { + e.printStackTrace(); + } + + + }); + + } catch (Exception e) { + e.printStackTrace(); + } + + return view; + } + + private static void renderView(String actionName, Map parameters, Action action) throws Exception { + if (!action.getName().equalsIgnoreCase(actionName)) { + return;//same as continue + } + String packageName = action.getPackageName(); + Class aClass; + aClass = Class.forName(packageName); + Object instance = aClass.newInstance(); + + Method[] methods = aClass.getDeclaredMethods(); + Map methodMap = new HashMap(); + for (Method method : methods) { + method.setAccessible(true); + methodMap.put(method.getName(), method); + } + + invokeMethod("setName", parameters.get("name"), instance, methodMap); + invokeMethod("setPassword", parameters.get("password"), instance, methodMap); + String jsp = invokeMethod("execute", null, instance, methodMap); + + String message = invokeMethod("getMessage", null, instance, methodMap); + + Map params = new HashMap(); + params.put("message", message); + view = new View(); + view.setParameters(params); + List results = action.getResults(); + results.forEach(temp -> { + if (temp.getName().equalsIgnoreCase(jsp)) { + view.setJsp(temp.getValue()); + } + + }); + } + + + + private static Object getBean(Class clz, String fileName) throws JAXBException { + JAXBContext context = JAXBContext.newInstance(clz); + Unmarshaller unmarshaller = context.createUnmarshaller(); + InputStream inputStream = Struts.class.getClassLoader().getResourceAsStream(fileName); + return unmarshaller.unmarshal(inputStream); + } + + + private static String invokeMethod(String methodName, String param, Object instance, Map map) throws IllegalAccessException, InvocationTargetException { + Method setNameMethod = map.get(methodName); + String invoke = null; + if (setNameMethod != null) { + if (param == null) { + invoke = (String) setNameMethod.invoke(instance); + return invoke; + } + invoke = (String) setNameMethod.invoke(instance, param); + } + + + return invoke; + } + +} \ No newline at end of file diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/StrutsTest.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/StrutsTest.java new file mode 100644 index 0000000000..68f204e252 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/StrutsTest.java @@ -0,0 +1,43 @@ +package com.yang; + +import junit.framework.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")); + } +} \ No newline at end of file diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/View.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/View.java new file mode 100644 index 0000000000..e443b9c759 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/View.java @@ -0,0 +1,27 @@ +package com.yang; + +import java.util.Map; + +/** + * Created by Dev_yang on 2017/3/5. + */ +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + + public void setJsp(String jsp) { + this.jsp = jsp; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } +} diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Action.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Action.java new file mode 100644 index 0000000000..f79864106a --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Action.java @@ -0,0 +1,58 @@ +package com.yang.bean; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import java.io.Serializable; +import java.util.List; + +/** + * Created by Dev_yang on 2017/3/5. + */ +public class Action implements Serializable{ + + private List results; + + private String name; + + private String packageName; + + + @XmlElement(name = "result") + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } + + + @XmlAttribute(name="name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @XmlAttribute(name = "class") + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + + @Override + public String toString() { + return "Action{" + + "results=" + results + + ", name='" + name + '\'' + + ", packageName='" + packageName + '\'' + + '}'; + } +} diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Result.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Result.java new file mode 100644 index 0000000000..9dd66cac04 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Result.java @@ -0,0 +1,40 @@ +package com.yang.bean; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlValue; +import java.io.Serializable; + +/** + * Created by Dev_yang on 2017/3/5. + */ +public class Result implements Serializable{ + + private String name; + private String value; + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return "Result{" + + "name='" + name + '\'' + + ", value='" + value + '\'' + + '}'; + } +} diff --git a/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Struts.java b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Struts.java new file mode 100644 index 0000000000..ad16ccc057 --- /dev/null +++ b/group11/501294009/JavaProject/module2/src/main/java/com/yang/bean/Struts.java @@ -0,0 +1,34 @@ + +package com.yang.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.List; + + + +@XmlRootElement(name = "struts") +public class Struts implements Serializable{ + + private List actions; + + + @XmlElement(name = "action") + public List getActions() { + return actions; + } + + + public void setActions(List actions) { + this.actions = actions; + } + + + @Override + public String toString() { + return "Struts{" + + "actions=" + actions + + '}'; + } +} diff --git a/group11/501294009/JavaProject/module2/src/main/resources/struts.xml b/group11/501294009/JavaProject/module2/src/main/resources/struts.xml new file mode 100644 index 0000000000..9c989a77e3 --- /dev/null +++ b/group11/501294009/JavaProject/module2/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/group11/542194147/myDataStructure/src/com/coderising/download/DownloadThread.java b/group11/542194147/myDataStructure/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..b12ad98379 --- /dev/null +++ b/group11/542194147/myDataStructure/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,26 @@ +package com.coderising.download; + +import java.io.IOException; + +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(){ + try { + conn.read(startPos, endPos); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/group11/542194147/myDataStructure/src/com/coderising/download/FileDownloader.java b/group11/542194147/myDataStructure/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..75ade93046 --- /dev/null +++ b/group11/542194147/myDataStructure/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,79 @@ +package com.coderising.download; + +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; + + int downloadThreadNum=3; + + 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 downloadBlock=length/3; + int appendBlock=length%3; + RandomAccessFile rdaFile=new RandomAccessFile("downloadFile","wr"); + for(int i=0;i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + Node p=head; Node q=null; Node front=null; + while(p!=null){ + q=p.next; + p.next=front; + front=p; + p=q; + } + head=front; + } + + /** + * 删除一个单链表的前半部分 + * 例如: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(MyLinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(MyLinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public MyLinkedList intersection( MyLinkedList list){ + return null; + } } diff --git a/group11/729245768/DataStructure/src/main/coding_170309/DownloadThread.java b/group11/729245768/DataStructure/src/main/coding_170309/DownloadThread.java new file mode 100644 index 0000000000..6380e5d9c1 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/DownloadThread.java @@ -0,0 +1,37 @@ +package main.coding_170309; + +import main.coding_170309.api.Connection; + +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * Created by peter on 2017/3/9. + */ +public class DownloadThread implements Runnable { + Connection conn; + int startPos; + int endPos; + public DownloadThread(Connection conn,int startPos,int endPos){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + + @Override + public void run() { + try { + try { + String fileName = "d://liying"+conn.getURL().substring(conn.getURL().lastIndexOf('.')); + byte[] data= conn.read(startPos,endPos); + RandomAccessFile randomAccessFile = new RandomAccessFile(fileName,"rw"); + randomAccessFile.seek(startPos); + randomAccessFile.write(data,0,data.length); + randomAccessFile.close(); + } finally { + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/FileDownloader.java b/group11/729245768/DataStructure/src/main/coding_170309/FileDownloader.java new file mode 100644 index 0000000000..ac4d38a365 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/FileDownloader.java @@ -0,0 +1,69 @@ +package main.coding_170309; + +import main.coding_170309.api.Connection; +import main.coding_170309.api.ConnectionException; +import main.coding_170309.api.ConnectionManager; +import main.coding_170309.api.DownloadListener; +import main.coding_170309.impl.ConnectionManagerImpl; +import main.coding_170309.impl.DownloadListenerImpl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Created by peter on 2017/3/9. + */ +public class FileDownloader { + String url; + ConnectionManager cm; + DownloadListener listener; + public FileDownloader(String url){ + this.url = url; + } + + public void execute() throws ConnectionException, IOException { + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + cm = new ConnectionManagerImpl(); + Connection conn = cm.open(url); + HttpURLConnection urlConnection =(HttpURLConnection) new URL(url).openConnection(); + int length = urlConnection.getContentLength(); + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + ExecutorService executor = Executors.newFixedThreadPool(3); + if(length>0){ + executor.execute(new DownloadThread(conn,0,length/3-1)); + executor.execute(new DownloadThread(conn,length/3,length/3*2-1)); + executor.execute(new DownloadThread(conn,length/3*2,length)); + }else{ + executor.execute(new DownloadThread(conn,0,1024*150)); + executor.execute(new DownloadThread(conn,1024*150,1024*300)); + executor.execute(new DownloadThread(conn,1024*300,1024*450)); + } + + + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + setListener(new DownloadListenerImpl(executor)); + listener.notifyFinshed(); + + } + 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/729245768/DataStructure/src/main/coding_170309/Hello.java b/group11/729245768/DataStructure/src/main/coding_170309/Hello.java new file mode 100644 index 0000000000..9a9ebaf7a9 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/Hello.java @@ -0,0 +1,22 @@ +package main.coding_170309; + +import main.coding_170309.api.ConnectionException; + +import java.io.IOException; + +/** + * Created by peter on 2017/3/9. + */ +public class Hello { + public static void main(String[] args) { + String url = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4162473607,1717166705&fm=23&gp=0.jpg"; + FileDownloader downloader = new FileDownloader(url); + try { + downloader.execute(); + } catch (ConnectionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/LinkedList.java b/group11/729245768/DataStructure/src/main/coding_170309/LinkedList.java new file mode 100644 index 0000000000..8784d252f3 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/LinkedList.java @@ -0,0 +1,271 @@ +package main.coding_170309; + +/** + * Created by peter on 2017/3/10. + */ +public class LinkedList implements List { + private Node head; + public LinkedList(){ + head = new Node(); + head.data = null; + head.next = null; + } + @Override + public void add(Object o) { + Node p = head; + while (p.next!=null){ + p=p.next; + } + Node node = new Node(); + node.data = o; + node.next = null; + p.next = node; + + } + + @Override + public void add(Object o, int index) { + if(index<0||index>getSize()){ + throw new ArrayIndexOutOfBoundsException("插入位置不合法"); + } + int i =0; + Node p =head; + while (i=getSize()){ + throw new ArrayIndexOutOfBoundsException("数组越界"); + } + int i =0 ; + Node p = head.next; + while (i=getSize()){ + throw new ArrayIndexOutOfBoundsException("不合法的index"); + } + int i = 0; + Node p =head; + while (i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + Node p = head.next; + head.next = null; + while (p!=null){ + add(p.data,0); + p = p.next; + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + int removeSize = getSize()/2; + for(int i=0;i=getSize()){ + throw new ArrayIndexOutOfBoundsException("下标越界"); + } + if(length<0){ + throw new IllegalArgumentException("长度不能为负"); + } + for(int index = i;index101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + int length = list.getSize(); + int[] data= new int[length]; + for(int i=0;i=max){ + throw new IllegalArgumentException("max必须不能比min小"); + } + int length = 0;//满足条件的个数 + Node p =head.next; + Node q = head; + Node startPos=null,endPos=null; + boolean isStarted=false; + while (p!=null){ + if((int)p.data>min&&!isStarted){ + startPos = q; + isStarted = true; + } + if((int)p.data>=max){ + endPos = p; + break; + } + q = p; + p = p.next; + } + //存在三种情况:startPos和endPos均为null,startPos不为null,endPos为null,startPos不为null和endPos不为null + startPos.next = endPos; + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + Node p =this.head.next; + Node q = list.head.next; + LinkedList newList = new LinkedList(); + while (p!=null&&q!=null){ + if((int)p.data>(int)q.data){ + q = q.next; + }else if((int)p.data==(int)q.data){ + newList.add(p.data); + p = p.next; + q = q.next; + }else { + p = p.next; + } + } + while (p!=null){ + newList.add(p.data); + p = p.next; + } + while (q!=null){ + newList.add(q.data); + q = q.next; + } + return newList; + } +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/List.java b/group11/729245768/DataStructure/src/main/coding_170309/List.java new file mode 100644 index 0000000000..78a8ce41a7 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/List.java @@ -0,0 +1,12 @@ +package main.coding_170309; + +/** + * Created by peter on 2017/3/10. + */ +public interface List { + public void add(Object o); + public void add(Object o ,int index); + public Object get(int index); + public Object remove(int index); + public int getSize(); +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/api/Connection.java b/group11/729245768/DataStructure/src/main/coding_170309/api/Connection.java new file mode 100644 index 0000000000..c67a52b299 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/api/Connection.java @@ -0,0 +1,30 @@ +package main.coding_170309.api; + +import java.io.IOException; + +/** + * Created by peter on 2017/3/9. + */ +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(); + /** + * 获取url + */ + public String getURL(); +} + diff --git a/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionException.java b/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionException.java new file mode 100644 index 0000000000..8d4624647e --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionException.java @@ -0,0 +1,7 @@ +package main.coding_170309.api; + +/** + * Created by peter on 2017/3/9. + */ +public class ConnectionException extends Exception { +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionManager.java b/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionManager.java new file mode 100644 index 0000000000..e3746ebfb6 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/api/ConnectionManager.java @@ -0,0 +1,13 @@ +package main.coding_170309.api; + +/** + * Created by peter on 2017/3/9. + */ +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/api/DownloadListener.java b/group11/729245768/DataStructure/src/main/coding_170309/api/DownloadListener.java new file mode 100644 index 0000000000..324eabba73 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/api/DownloadListener.java @@ -0,0 +1,8 @@ +package main.coding_170309.api; + +/** + * Created by peter on 2017/3/9. + */ +public interface DownloadListener { + public void notifyFinshed(); +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionImpl.java b/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionImpl.java new file mode 100644 index 0000000000..ed015618bc --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionImpl.java @@ -0,0 +1,52 @@ +package main.coding_170309.impl; + +import main.coding_170309.api.Connection; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Arrays; + +/** + * Created by peter on 2017/3/9. + */ +public class ConnectionImpl implements Connection { + private String url; + private HttpURLConnection urlConnection; + + public ConnectionImpl(String url) { + this.url = url; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + urlConnection = (HttpURLConnection) new URL(url).openConnection(); + urlConnection.setRequestProperty("Range","bytes="+startPos+"-"+endPos);//从指定位置开始 + InputStream in = urlConnection.getInputStream(); + byte[] data = new byte[endPos-startPos+1]; + byte[] temp = new byte[1024]; + int pointer=0;//表示data每次偏移量 + int length ;//表示一次能读取的bit数 + while ((length=in.read(temp,0,temp.length))!=-1){ + System.arraycopy(temp,0,data,pointer,length); + pointer+=length; + } + return Arrays.copyOf(data,pointer); + } + + @Override + public int getContentLength() { + return urlConnection.getContentLength(); + } + + @Override + public String getURL() { + return url; + } + + @Override + public void close() { + urlConnection.disconnect(); + } +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionManagerImpl.java b/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..7b97153076 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/impl/ConnectionManagerImpl.java @@ -0,0 +1,16 @@ +package main.coding_170309.impl; + +import main.coding_170309.api.Connection; +import main.coding_170309.api.ConnectionException; +import main.coding_170309.api.ConnectionManager; + +/** + * Created by peter on 2017/3/9. + */ +public class ConnectionManagerImpl implements ConnectionManager { + @Override + public Connection open(String url) throws ConnectionException { + Connection conn = new ConnectionImpl(url); + return conn; + } +} diff --git a/group11/729245768/DataStructure/src/main/coding_170309/impl/DownloadListenerImpl.java b/group11/729245768/DataStructure/src/main/coding_170309/impl/DownloadListenerImpl.java new file mode 100644 index 0000000000..f496a0e126 --- /dev/null +++ b/group11/729245768/DataStructure/src/main/coding_170309/impl/DownloadListenerImpl.java @@ -0,0 +1,25 @@ +package main.coding_170309.impl; + +import main.coding_170309.api.DownloadListener; + +import java.util.concurrent.ExecutorService; + +/** + * Created by peter on 2017/3/9. + */ +public class DownloadListenerImpl implements DownloadListener { + private ExecutorService executor; + public DownloadListenerImpl(ExecutorService executor){ + this.executor = executor; + } + @Override + public void notifyFinshed() { + executor.shutdown(); + while (true){ + if(executor.isTerminated()){ + break; + } + } + System.out.println("网络文件下载完成"); + } +} diff --git a/group11/729245768/DataStructure/tests/main/coding_170309/LinkedListTest.java b/group11/729245768/DataStructure/tests/main/coding_170309/LinkedListTest.java new file mode 100644 index 0000000000..797e9d5f41 --- /dev/null +++ b/group11/729245768/DataStructure/tests/main/coding_170309/LinkedListTest.java @@ -0,0 +1,167 @@ +package main.coding_170309; + +import junit.framework.TestCase; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +/** + * Created by peter on 2017/3/11. + */ +public class LinkedListTest extends TestCase { + LinkedList linkedList; + @Before + public void setUp() throws Exception { + linkedList = new LinkedList(); + } + + @After + public void tearDown() throws Exception { + linkedList = null; + } + + @org.junit.Test + public void testAdd() throws Exception { + linkedList.add(1); + linkedList.add(2); + System.out.println(linkedList); + } + + @Test + public void testAdd1() throws Exception { + linkedList.add(12,0); + linkedList.add(15,1); + linkedList.add(20,1); + System.out.println(linkedList); + } + + @Test + public void testGet() throws Exception { + linkedList.add(12); + Assert.assertEquals(12,(int)linkedList.get(0)); + } + + @Test + public void testRemove() throws Exception { + linkedList.add(15); + linkedList.add(20); + linkedList.remove(0); + System.out.println(linkedList.getSize()); + } + + @Test + public void testGetSize() throws Exception { + linkedList.add(15); + linkedList.add(25); + linkedList.add(30); + linkedList.add(45); + System.out.println(linkedList.getSize()); + } + + @Test + public void testReverse() throws Exception { + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + System.out.println(linkedList); + linkedList.reverse(); + System.out.println(linkedList); + } + + @Test + public void testRemoveFirstHalf() throws Exception { + linkedList.add(10); + linkedList.add(11); + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(15); + System.out.println(linkedList); + linkedList.removeFirstHalf(); + System.out.println(linkedList); + } + + @Test + public void testRemove1() throws Exception { + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.add(5); + linkedList.remove(1,2); + System.out.println(linkedList); + } + + @Test + public void testGetElements() throws Exception { + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(15); + linkedList.add(16); + LinkedList list = new LinkedList(); + list.add(2); + list.add(3); + list.add(4); + int[] data = linkedList.getElements(list); + System.out.println(Arrays.toString(data)); + } + + @Test + public void testSubtract() throws Exception { + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(15); + linkedList.add(16); + LinkedList list = new LinkedList(); + list.add(12); + list.add(14); + list.add(15); + linkedList.subtract(list); + System.out.println(linkedList); + } + + @Test + public void testRemoveDuplicateValues() throws Exception { + linkedList.add(10); + linkedList.add(11); + linkedList.add(11); + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(14); + } + + @Test + public void testRemoveRange() throws Exception { + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.add(5); + linkedList.removeRange(2,4); + System.out.println(linkedList); + } + + @Test + public void testIntersection() throws Exception { + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(15); + linkedList.add(16); + LinkedList list = new LinkedList(); + list.add(12); + list.add(14); + list.add(15); + list.add(17); + list.add(18); + System.out.println(linkedList.intersection(list)); + + } + +} \ No newline at end of file diff --git a/group11/996108220/src/com/coderising/download/DownloadThread.java b/group11/996108220/src/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..79c738753b --- /dev/null +++ b/group11/996108220/src/com/coderising/download/DownloadThread.java @@ -0,0 +1,48 @@ +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.DownloadListener; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + boolean status=false; + CyclicBarrier barrier; + + public DownloadThread( Connection conn, int startPos, int endPos,CyclicBarrier barrier){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.barrier=barrier; + } + public void run(){ + try { + + byte[] buffer=conn.read(startPos, endPos); + RandomAccessFile fos = new RandomAccessFile(FileDownloader.SAVE_FILE, "rw"); + fos.seek(startPos); + fos.write(buffer, 0, endPos-startPos); + fos.close(); + barrier.await(); + + } catch (Exception e) { + // TODO Auto-generated catch block + + e.printStackTrace(); + } + + System.out.println("线程" + this.getId() + "已经完成"); + + } + + +} diff --git a/group11/996108220/src/com/coderising/download/FileDownloader.java b/group11/996108220/src/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..9fb1c8086d --- /dev/null +++ b/group11/996108220/src/com/coderising/download/FileDownloader.java @@ -0,0 +1,93 @@ +package com.coderising.download; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +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; + + +public class FileDownloader { + + public static File SAVE_FILE= new File("f:/abc.jpg");; + String url; + DownloadListener listener; + ConnectionManager cm; + int threadNumber = 3; + + + 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方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + CyclicBarrier barrier=new CyclicBarrier(threadNumber, new Runnable() { + + @Override + public void run() { + // TODO Auto-generated method stub + listener.notifyFinished(); + } + }); + Connection conn =null; + try { + conn = cm.open(this.url); + int length = conn.getContentLength(); + byte[] buf = new byte[8192]; + FileOutputStream fos; + fos = new FileOutputStream(FileDownloader.SAVE_FILE); + long m = length/ buf.length; + for (long i = 0; i < m; i++) { + fos.write(buf, 0, buf.length); + } + fos.write(buf, 0, (int)(conn.getContentLength() % buf.length)); + fos.close(); + //启动下载线程 + int fragment = length / threadNumber; + for (int i = 0; i < threadNumber-1; i++) { + new DownloadThread(conn,i*fragment,(i+1)*fragment-1,barrier).start(); + } + new DownloadThread(conn,(threadNumber-1)*fragment,length-1,barrier).start(); + barrier.await(); + } catch (Exception 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/group11/996108220/src/com/coderising/download/FileDownloaderTest.java b/group11/996108220/src/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..323febec1b --- /dev/null +++ b/group11/996108220/src/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,57 @@ +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://pic17.nipic.com/20111102/3707281_235344313129_2.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/group11/996108220/src/com/coderising/download/api/Connection.java b/group11/996108220/src/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..39f87cd2fa --- /dev/null +++ b/group11/996108220/src/com/coderising/download/api/Connection.java @@ -0,0 +1,25 @@ +package com.coderising.download.api; + +import java.io.IOException; +import java.net.URLConnection; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public URLConnection connection=null; + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/group11/996108220/src/com/coderising/download/api/ConnectionException.java b/group11/996108220/src/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..8dbfe95dda --- /dev/null +++ b/group11/996108220/src/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group11/996108220/src/com/coderising/download/api/ConnectionManager.java b/group11/996108220/src/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..fb44ede457 --- /dev/null +++ b/group11/996108220/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/group11/996108220/src/com/coderising/download/api/DownloadListener.java b/group11/996108220/src/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..4cd0b3eab1 --- /dev/null +++ b/group11/996108220/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/group11/996108220/src/com/coderising/download/impl/ConnectionImpl.java b/group11/996108220/src/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..425d1b272f --- /dev/null +++ b/group11/996108220/src/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,62 @@ +package com.coderising.download.impl; + + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; + +import com.coderising.download.api.Connection; + + +public class ConnectionImpl implements Connection{ + URL url; + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + URLConnection connection=url.openConnection(); + InputStream ins =connection.getInputStream(); + byte[] buffer = new byte[endPos-startPos+1]; +// ins.skip(startPos); +// ins.read(buffer,0, endPos-startPos); + int at = startPos; + long amt=0; + while(at > 0) { + amt = ins.skip(at-amt); + if (amt<=0) { + break; + } + at -= amt; + } + int curPos =0; + while(true){ + int readByte = ins.read(buffer,curPos, endPos-startPos-curPos); + if(readByte <=0){ + break; + } + curPos= readByte + curPos; + } + ins.close(); + return buffer; + } + + @Override + public int getContentLength() { + + try { + return url.openConnection().getContentLength(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return -1; + } + + @Override + public void close() { + + + } + +} diff --git a/group11/996108220/src/com/coderising/download/impl/ConnectionManagerImpl.java b/group11/996108220/src/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..768e2cc250 --- /dev/null +++ b/group11/996108220/src/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,30 @@ +package com.coderising.download.impl; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; + +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 { + + try { + ConnectionImpl conn=null; + conn=new ConnectionImpl(); + conn.url =new URL(url); + return conn; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + + } + +} diff --git a/group11/996108220/src/com/coderising/litestruts/Struts.java b/group11/996108220/src/com/coderising/litestruts/Struts.java index 8f961f2175..84c7578e91 100644 --- a/group11/996108220/src/com/coderising/litestruts/Struts.java +++ b/group11/996108220/src/com/coderising/litestruts/Struts.java @@ -153,15 +153,18 @@ private static View updaView(View view,ActionConfig actionConfig,String message) // System.out.println(results.item(i).getTextContent()); // } // } -// -//// NamedNodeMap name = beans.item(0).getAttributes(); + +// NamedNodeMap name = beans.item(0).getAttributes(); +// NodeList results = doc.getElementsByTagName("struts"); +// for (int i = 0; i < results.getLength(); i++) { +// System.out.println(results.item(i).getAttributes().getNamedItem("name").getNodeValue()); +// System.out.println(results.item(i).getTextContent()); +// } // // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } - - -// } +// } } diff --git a/group11/996108220/src/com/coding/basic/LinkedList.java b/group11/996108220/src/com/coding/basic/LinkedList.java index be0b354bc2..8f5b928e02 100644 --- a/group11/996108220/src/com/coding/basic/LinkedList.java +++ b/group11/996108220/src/com/coding/basic/LinkedList.java @@ -1,14 +1,16 @@ package com.coding.basic; + import java.util.NoSuchElementException; -public class LinkedList implements List { + +public class LinkedList implements List { private Node head; private int size=0; /** * 增加节点 */ - public void add(Object o){ + public void add(T o){ if(size==0){ head=new Node(); head.data=o; @@ -23,7 +25,7 @@ public void add(Object o){ /** * 在index(0~size)处添加元素 */ - public void add(int index , Object o){ + public void add(int index , T o){ if(index<0||index>size){ System.out.println("index超出范围"+index); @@ -56,6 +58,16 @@ public Object get(int index){ return ptr; } } + public Node getNode(int index) { + if (index<0||index>=size) { + return null; + } + Node ptrNode=head; + for (int i = 0; i < index; i++) { + ptrNode=ptrNode.next; + } + return ptrNode; + } /** * 移除index(0~size-1)的元素 */ @@ -79,14 +91,14 @@ public int size(){ return size; } - public void addFirst(Object o){ + public void addFirst(T o){ Node ptr=head; head=new Node(); head.data=o; head.next=ptr; size++; } - public void addLast(Object o){ + public void addLast(T o){ Node ptr=head; for(int i=1;i{ + T data; Node next; } public static void main(String args[]){ LinkedList list=new LinkedList(); - list.add(0); list.add(1); list.add(2); + list.add(2); list.add(3); list.add(4); + list.add(4); list.add(5); list.add(6); -// list.add(7,9); -// System.out.println(list.remove(5)); -// System.out.println(list.remove(5)); -// System.out.println(list.remove(6)); -// System.out.println(list.size()); -// Node ptr=list.head; -// do{ -// System.out.print(ptr.data); -// ptr=ptr.next; -// }while(ptr!=null); + list.add(6); + LinkedList list2=new LinkedList(); + list2.add(0); + list2.add(0); + list2.add(1); + list2.add(2); + list2.add(3); + list2.add(5); + list2.add(6); + list2.add(7); + list.removeRange(5,7); Iterator itr=list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + if (size==0||size==1) { + return ; + } + else if (size==2) { + Node ptr=head.next; + head.next=null; + ptr.next=head; + head=ptr; + } + else{ + Node pre=head; + Node ptr=head.next; + while (ptr.next!=null) { + Node node=ptr.next; + ptr.next=pre; + pre=ptr; + ptr=node; + } + ptr.next=pre; + head.next=null; + head=ptr; + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + Node ptr=head; + for (int i = 1; i < size/2; i++) { + ptr=ptr.next; + } + head=ptr.next; + size=size-size/2; + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + if (i>=size||i<0||i+length-1>=size) { + return; + } + Node ptr=head; + if (i==0) { + for (int j = 0; j < length; j++) { + ptr=ptr.next; + } + head=ptr; + } + else { + ptr=head; + Node pre=null; + for (int j = 0; j < i+length; j++) { + if (j==i-1) { + pre=ptr; + } + ptr=ptr.next; + } + pre.next=ptr; + } + 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){ + Node ptrNode=list.head; + int[] array=new int[list.size()]; + int i=0; + while (ptrNode!=null) { + int index=Integer.parseInt(String.valueOf(ptrNode.data)); + array[i++]=Integer.parseInt(String.valueOf(this.getNode(index).data)); + ptrNode=ptrNode.next; + } + return array; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在list中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + Node ptr=list.head; + if (list.size()==0||size==0) { + return; + } + while (ptr!=null) { + delete(ptr.data); + ptr=ptr.next; + } + + } + + private void delete(Comparable data) { + if (size==0) { + return; + } + else if (size==1) { + if (head.data.compareTo(data)==0) { + head=null; + size--; + } + } + else { + if (head.data.compareTo(data)==0) { + size--; + head=size==0?null:head.next; + return; + } + Node pre=head; + Node ptr=head.next; + do{ + if (ptr.data.compareTo(data)==0) { + pre.next=ptr.next; + size--; + break; + } + else { + pre=ptr; + ptr=ptr.next; + } + }while (ptr!=null); + } + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + removeDuplicateValues(head); + } + + private void removeDuplicateValues(Node node) { + if (node.next==null||node==null) { + return; + } + else { + if (node.data.compareTo(node.next.data)==0) { + node.next=node.next.next; + size--; + removeDuplicateValues(node); + } + else { + removeDuplicateValues(node.next); + } + } + + } + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + if (size==0) { + return; + } + else if (size==1) { + if (head.data.compareTo(min)>0&&head.data.compareTo(max)<0) { + head=null; + size--; + } + else { + return; + } + } + else { + Node pre=null; + Node ptr=head; + Node tail=null; + int num=0; + + if (ptr==head&&(head.data.compareTo(min)>0&&head.data.compareTo(max)<0)) { + while (ptr!=null) { + if (ptr.data.compareTo(max)>=0) { + head=ptr; + size=size-num; + return; + } + else { + ptr=ptr.next; + num++; + } + } + size=0; + head=null; + return; + } + else if (head.data.compareTo(min)<=0) { + pre=head; + ptr=head.next; + while (ptr!=null) { + if (ptr.data.compareTo(min)<=0) { + pre=ptr; + ptr=ptr.next; + } + else if (ptr.data.compareTo(min)>0&&ptr.data.compareTo(max)<0) { + ptr=ptr.next; + num++; + } + else { + tail=ptr; + break; + } + } + if (pre==head) { + return; + } + else if (pre!=head&&tail!=null) { + size=size-num; + pre.next=tail; + }else { + pre.next=null; + size=size-num; + } + } + + + + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + LinkedList linkedList=new LinkedList(); + Node node1=head; Node node2=list.head; + while (node1!=null&&node2!=null) { + if (node1.data==node2.data) { + linkedList.add(node1.data); + node1=node1.next; + node2=node2.next; + } + else if (Integer.parseInt(String.valueOf(node1.data)) { //用链表实现队列 private LinkedList elementData = new LinkedList(); - public void enQueue(Object o){ + public void enQueue(T o){ elementData.addLast(o);; } public Object deQueue(){ diff --git a/group17/1204187480/code/homework/basic/src/main/java/com/coding/basic/LinkedList.java b/group17/1204187480/code/homework/basic/src/main/java/com/coding/basic/LinkedList.java index 7174cb9cdf..6a94ded0a9 100644 --- a/group17/1204187480/code/homework/basic/src/main/java/com/coding/basic/LinkedList.java +++ b/group17/1204187480/code/homework/basic/src/main/java/com/coding/basic/LinkedList.java @@ -1,147 +1,247 @@ -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)); - } - } - - 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/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/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/liuxin/.project b/group22/1014331282/Mywork_LX/.project similarity index 89% rename from liuxin/.project rename to group22/1014331282/Mywork_LX/.project index b6d8ce6204..1290d27942 100644 --- a/liuxin/.project +++ b/group22/1014331282/Mywork_LX/.project @@ -1,17 +1,17 @@ - - - coding2017 - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - + + + 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/group22/1014331282/Mywork_LX/src/week1_0306/List.java b/group22/1014331282/Mywork_LX/src/week1_0306/List.java new file mode 100644 index 0000000000..7ec758f832 --- /dev/null +++ b/group22/1014331282/Mywork_LX/src/week1_0306/List.java @@ -0,0 +1,18 @@ +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/group24/330657387/src/com/coding/basic/List.java b/group22/1258890344/src/com/coding/basic/List.java similarity index 100% rename from group24/330657387/src/com/coding/basic/List.java rename to group22/1258890344/src/com/coding/basic/List.java 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/liuxin/src/com/coderising/litestruts/LoginAction.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/LoginAction.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/LoginAction.java rename to group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/LoginAction.java 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/liuxin/src/com/coderising/litestruts/StrutsTest.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/StrutsTest.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/StrutsTest.java rename to group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/StrutsTest.java diff --git a/liuxin/src/com/coderising/litestruts/View.java b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/View.java similarity index 100% rename from liuxin/src/com/coderising/litestruts/View.java rename to group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/View.java diff --git a/liuxin/src/com/coderising/litestruts/struts.xml b/group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/struts.xml similarity index 100% rename from liuxin/src/com/coderising/litestruts/struts.xml rename to group22/1335499238/coding2017/src/main/java/com/coderising/litestruts/struts.xml 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 { + //pred��succ�������ԣ�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 ��Ԫ�� �� ע��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/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/liuxin/.gitignore b/group22/573535234/githubTutorial/.gitignore similarity index 100% rename from liuxin/.gitignore rename to group22/573535234/githubTutorial/.gitignore 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 ��Ԫ�� �� ע��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/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/liuxin/src/com/coding/basic/List.java b/group22/592864103/List.java similarity index 95% rename from liuxin/src/com/coding/basic/List.java rename to group22/592864103/List.java index 396b1f6416..10d13b5832 100644 --- a/liuxin/src/com/coding/basic/List.java +++ b/group22/592864103/List.java @@ -1,9 +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(); -} +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/group24/330657387/src/com/coding/basic/Stack.java b/group22/592864103/Stack.java similarity index 100% rename from group24/330657387/src/com/coding/basic/Stack.java rename to group22/592864103/Stack.java 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 ��Ԫ�� �� ע��i��0��ʼ + * + * @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��ʼ�ƶ���ע��index��0��ʼ�� + * ����Ҫ+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��ʼ�ƶ���ע��index��0��ʼ�� + * ����Ҫ+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�еĹ�ʽ��Դ����ʹ�õ�����1������2// + 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 ��Ԫ�� �� ע��i��0��ʼ + * @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 + * @2017��3��17������10:55:39 + * + */ +public class Test { + + /**Description: + * @param args + * @author HuangLiang 2017��3��17�� ����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/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java b/group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java similarity index 96% rename from group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java rename to group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java index 5496d8084d..340d542dec 100644 --- a/group17/1204187480/code/homework/coderising/src/main/java/com/coderising/action/LoginAction.java +++ b/group23/729693763/Second_Homework2/src/com/danny/hw2/LoginAction.java @@ -1,4 +1,4 @@ -package com.coderising.action; +package com.danny.hw2; /** * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 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/group23/769232552/coding/src/main/java/code01/Iterator.java b/group23/769232552/coding/src/main/java/code01/Iterator.java new file mode 100644 index 0000000000..b4074067bb --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/Iterator.java @@ -0,0 +1,7 @@ +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/group23/769232552/coding/src/main/java/code01/Stack.java b/group23/769232552/coding/src/main/java/code01/Stack.java new file mode 100644 index 0000000000..dbaeb91a48 --- /dev/null +++ b/group23/769232552/coding/src/main/java/code01/Stack.java @@ -0,0 +1,31 @@ +package code01; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + Object result = null; + if(elementData.size()!=0) { + result = elementData.remove(elementData.size() - 1); + } + return result; + } + + public Object peek(){ + Object result = null; + if(elementData.size()!=0) { + result = elementData.get(elementData.size() - 1); + } + return result; + } + public boolean isEmpty(){ + return elementData.size() == 0; + } + 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/.gitignore.bak b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore similarity index 70% rename from .gitignore.bak rename to group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore index ec55baf87d..2c93a035dc 100644 --- a/.gitignore.bak +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/.gitignore @@ -1,16 +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 +*.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; + + + } + + /** + * ���������Ѿ�����õ��������飬 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 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; + } + + /** + * 쳲���������Ϊ��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=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") , + �Ǿ�Ӧ�õ��� setName��setPassword���� + + 2. ͨ��������ö����exectue ������ ����÷���ֵ������"success" + + 3. ͨ�������ҵ����������getter���������� getMessage��, + ͨ�����������ã� ��ֵ�������γ�һ��HashMap , ���� {"message": "��¼�ɹ�"} , + �ŵ�View�����parameters + + 4. ����struts.xml�е� ����,�Լ�execute�ķ���ֵ�� ȷ����һ��jsp�� + �ŵ�View�����jsp�ֶ��С� + + */ + //��ȡ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/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/struts.xml b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/struts.xml new file mode 100644 index 0000000000..0582b7d4ea --- /dev/null +++ b/group24/1054283210/src/com/github/xiaozi123/coding2017/secondWork/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + 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 +CSDN��http://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/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/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs b/group27/1067041567/TestColleaction/.settings/org.eclipse.core.resources.prefs similarity index 64% rename from group27/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs rename to group27/1067041567/TestColleaction/.settings/org.eclipse.core.resources.prefs index 3e64772097..99f26c0203 100644 --- a/group27/1252327158/task1_20170312/.settings/org.eclipse.core.resources.prefs +++ b/group27/1067041567/TestColleaction/.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 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; + } + + /** + * ���������Ѿ�����õ��������飬 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){ + 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; + } + + /** + * 쳲���������Ϊ��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[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/liuxin/src/com/coding/basic/BinaryTreeNode.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java similarity index 87% rename from liuxin/src/com/coding/basic/BinaryTreeNode.java rename to group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java index 266eff3d56..37fd8a3d4f 100644 --- a/liuxin/src/com/coding/basic/BinaryTreeNode.java +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/BinaryTreeNode.java @@ -1,32 +1,34 @@ -package com.coding.basic; - -public class BinaryTreeNode { - - private Object data; - private BinaryTreeNode left; - private BinaryTreeNode right; - - public Object getData() { - return data; - } - public void setData(Object data) { - this.data = data; - } - public BinaryTreeNode getLeft() { - return left; - } - public void setLeft(BinaryTreeNode left) { - this.left = left; - } - public BinaryTreeNode getRight() { - return right; - } - public void setRight(BinaryTreeNode right) { - this.right = right; - } - - public BinaryTreeNode insert(Object o){ - return null; - } - -} +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/group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java new file mode 100644 index 0000000000..6e2869bd04 --- /dev/null +++ b/group27/514402862/dataStructure/src/main/java/com/zzl/util/Queue.java @@ -0,0 +1,24 @@ +package com.zzl.util; + +public class Queue { + + private ArrayList elementData = new ArrayList(); + + public void enQueue(Object o){ + elementData.add(o); + } + + public Object deQueue(){ + return elementData.remove(0); + } + + public boolean isEmpty(){ + int len = elementData.size(); + + return len == 0; + } + + public int size(){ + return elementData.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/src/com/coderising/litestruts/Struts.java b/liuxin/data-structure/src/com/coderising/litestruts/Struts.java similarity index 96% rename from liuxin/src/com/coderising/litestruts/Struts.java rename to liuxin/data-structure/src/com/coderising/litestruts/Struts.java index 44cc35bf01..85e2e22de3 100644 --- a/liuxin/src/com/coderising/litestruts/Struts.java +++ b/liuxin/data-structure/src/com/coderising/litestruts/Struts.java @@ -1,34 +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; - } - -} +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/group24/330657387/src/com/coding/basic/BinaryTreeNode.java b/liuxin/data-structure/src/com/coding/basic/BinaryTreeNode.java similarity index 100% rename from group24/330657387/src/com/coding/basic/BinaryTreeNode.java rename to liuxin/data-structure/src/com/coding/basic/BinaryTreeNode.java 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/group24/330657387/src/com/coding/basic/Queue.java b/liuxin/data-structure/src/com/coding/basic/Queue.java similarity index 100% rename from group24/330657387/src/com/coding/basic/Queue.java rename to liuxin/data-structure/src/com/coding/basic/Queue.java diff --git a/liuxin/src/com/coding/basic/Stack.java b/liuxin/data-structure/src/com/coding/basic/Stack.java similarity index 87% rename from liuxin/src/com/coding/basic/Stack.java rename to liuxin/data-structure/src/com/coding/basic/Stack.java index 4bfe28057f..459ec560b4 100644 --- a/liuxin/src/com/coding/basic/Stack.java +++ b/liuxin/data-structure/src/com/coding/basic/Stack.java @@ -1,22 +1,24 @@ -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; + +import com.coding.basic.array.ArrayList; + +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/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/src/com/coderising/array/ArrayUtil.java b/liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java similarity index 95% rename from liuxin/src/com/coderising/array/ArrayUtil.java rename to liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java index 78845d06d0..45740e6d57 100644 --- a/liuxin/src/com/coderising/array/ArrayUtil.java +++ b/liuxin/data-structure/src/com/coding/basic/array/ArrayUtil.java @@ -1,96 +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; - } - - -} +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