参考 Sort的实现。提交博客连接。html
必须答辩才能得分java
输出排序前的数组; 命令行输入参数; 判断参数是否符合要求; 对排序好的数组遍历并输出第二列元素相同的toSort数组。
import java.util.*; public class MySort { public static void main(String [] args) { String [] toSort = { "aaa:10:1:1", "ccc:30:3:4", "bbb:50:4:5", "ddd:20:5:3", "eee:40:2:20"}; System.out.println("Before sort:");//输出排序前字符串数组 for (String str: toSort) System.out.println(str); int [] a=new int[toSort.length]; for(int i=0;i<toSort.length;i++){//对toSort每个元素用split进行划分,并储存进字符串数组list中 String [] list=toSort[i].split(":"); a[i]=Integer.parseInt(list[1]);//将list中第二个元素,即toSort中第二列元素存进a中 } Arrays.sort(a); System.out.println("After sort:"); for (int i = 0; i < a.length; i++)//对a中每一个元素 for (int j = 0; j < toSort.length; j++)//在toSort中每个元素的第二列中比较 if (a[i] == Integer.parseInt((toSort[j].split(":"))[1]))//若是两者相等 System.out.println(toSort[j]);//就输出该项元素 } public static int StringTest1(String str){ int a; String [] list=str.split(":"); a=Integer.parseInt(list[1]);//将list中第二个元素,即toSort中第二列元素存进a中 return a; } public static int[] StringTest2(String[] toSort){ int [] a=new int[toSort.length]; for(int i=0;i<toSort.length;i++){//对toSort每个元素用split进行划分,并储存进字符串数组list中 String [] list=toSort[i].split(":"); a[i]=Integer.parseInt(list[1]);//将list中第二个元素,即toSort中第二列元素存进a中 } Arrays.sort(a); return a; } }
import junit.framework.TestCase; import org.junit.Test; public class MySortTest extends TestCase { String [] toSort = { "aaa:10:1:1", "ccc:30:3:4", "bbb:50:4:5", "ddd:20:5:3", "eee:40:2:20"}; @Test public void testl() { assertEquals(10,MySort.StringTest1("aaa:10:1:1")); } public void test2() { assertEquals(20,MySort.StringTest2(toSort)[1]); } }