20155212Arrays和String测试_MySort

Arrays和String单元测试

在IDEA中以TDD的方式对String类和Arrays类进行学习

  • 测试相关方法的正常,错误和边界情况
    • String类
      • charAt
      • split
    • Arrays类
      • sort
      • binarySearch
  • 码云链接
  • 代码
/**
 * Created by radish608 on 17-5-10.
 */
import java.util.*;
import org.junit.Test;

import static java.util.Arrays.binarySearch;


public class SAtest {

    String teststring1 = "Hello World!";
    String teststring2 = " ";

    String teststring3 = "boo:and:foo";
    String[] teststring4 = new String[3];
    String[] teststring5 = new String[3];

    @Test
    public void StringTester()  {
        assert teststring1.charAt(0) == 'H' : "error1:charAt";
        assert teststring1.charAt(teststring1.length()-1) == '!' : "error2:charAt";
        assert teststring2.charAt(0) == teststring2.charAt(teststring2.length()-1) : "error3:charAt";

        teststring4 = teststring3.split(":");
        teststring5 = teststring3.split("o");

        assert teststring4[0].equals("boo") : "error4:split";
        assert teststring4[1].equals("and") : "error5:split";
        assert teststring4[2].equals("foo"): "error6:split";

        assert teststring5[0].equals("b") : "error7:split";
        assert teststring5[1].equals("") : "error8:split";
        assert teststring5[2].equals(":and:f") : "error9:split";

    }

    @Test
    public void ArraysTester() {
        int []testarr1 = { 1, 3, 5, 4, 2, 0};
        int []testarr2 = {2, 5, 7, 8, 9, 0, 10, 11, 13, 15, 19};

        Arrays.sort(testarr1);
        assert testarr1[1] == 1 : "error10:sort";

        assert binarySearch(testarr2, 0, testarr2.length-1, 5) == 1 : "error11:binarySearch";

    }


}


  • 截图

MySort

模拟实现Linux下Sort -t : -k 2的功能。参考 Sort的实现。提交码云链接和代码运行截图。

/**
 * Created by radish608 on 17-5-10.
 */
import java.util.*;

public class MySort1 {
    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);


        System.out.println("After sort:");
        int[] tmp = new int[toSort.length];
        String[][] string = new String [toSort.length][4];
        for (int i = 0; i < toSort.length; i++) {
            string[i] = toSort[i].split(":");
            tmp[i] = Integer.parseInt(string[i][1]);
        }
        Arrays.sort(tmp);
        for (int i = 0; i < tmp.length; i++) {
            for (int j = 0; j < toSort.length; j++) {
                if(tmp[i] == Integer.parseInt(string[j][1])){
                    System.out.println(toSort[j]);
                }
            }
        }
    }
}
  • 截图
posted @ 2017-05-11 23:13  0**  阅读(227)  评论(0编辑  收藏  举报