MySort(选做)

一、题目要求

  • 注意:研究sort的其他功能,要能改的动代码,需要答辩

  • 模拟实现Linux下Sort -t : -k 2的功能。

  • 要有伪代码,产品代码,测试代码(注意测试用例的设计)

  • 参考 Sort的实现。提交博客链接。

  • 必须答辩才能得分

二、代码

1.伪代码

输出排序前的数组;
命令行输入参数;
判断参数是否符合要求;
对排序好的数组遍历并输出第二列元素相同的toSort数组。

2.产品代码

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;
    }
}

3.测试代码

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]);
    }
}

三、实验截图

SP.参考资料

1.20175214 MySort(选做)
2.MySort作业与IO-Myhead
3.课下选做作业MySort

posted @ 2019-05-19 18:34  20175215丁文韬  阅读(238)  评论(0编辑  收藏  举报