为了便于讲授,拟通过两个简朴的业务类引出测试用例,一个是分段函数类,另一个是字符串处理惩罚类,在这节里我们先来熟悉这两个业务类。
分段函数类
分段函数Subsection类有两个函数,sign()是一个标记函数,而getValue(int d)函数成果如下:
当d < -2时,值为abs(d);
当-2≤d<2 且d!=0时,值为d*d;
当d=0时,值为100;
当2≤d时,值为d*d*d。
其代码如下图所示:
代码清单 错误!文档中没有指定样式的文字。分段函数
1. package chapter25;
2.
3. public class Subsection
4. {
5. public static int getValue(int d) {
6. if (d == 0) {
7. return 100;
8. } else if (d < -2) {
9. return Math.abs(d);
10. } else if (d >= -2 && d < 2) {
11. return d * d;
12. } else { //d >= 2
13. // if (d > 32) {
14. // return Integer.MAX_VALUE;
15. // }
16. return d * d * d;
17. }
18. }
19.
20. public static int sign(double d) {
21. if (d < 0) {
22. return -1;
23. } else if (d > 0) {
24. return 1;
25. } else {
26. return 0;
27. }
28. }
29. }
在getValue()要领中,当d>32时,d*d*d的值将高出int数据范例的最大值(32768),所以当d>32时,理应做非凡的处理惩罚,这里我们特意将这个非凡处理惩罚的代码注释掉(第13~15行),模仿一个潜在的Bug。
字符串处理惩罚类
由于尺度JDK中所提供的String类对字符串操纵成果有限,而字符串处理惩罚长短经常用的操纵,所以一般的系统都提供了一个本身的字符串处理惩罚类。下面就是一个字符串处理惩罚类,为了简朴,我们仅提供了一个将字符串转换成数组的要领string2Array(),其代码如下所示:
代码清单 错误!文档中没有指定样式的文字。字符串处理惩罚类
1. package chapter25;
2. public class StringUtils
3. {
4. public static String[] string2Array(String str, char splitChar, boolean trim) {
5. if (str == null) {
6. return null;
7. } else {
8. String tempStr = str;
9. int arraySize = 0; //数组巨细
10. String[] resultArr = null;
11. if (trim) { //假如需要删除头尾多余的脱离符
12. tempStr = trim(str, splitChar);
13. }
14. arraySize = getCharCount(tempStr, splitChar) + 1;
15. resultArr = new String[arraySize];
16. int fromIndex = 0, endIndex = 0;
17. for (int i = 0; i < resultArr.length; i++) {
18. endIndex = tempStr.indexOf(splitChar, fromIndex);
19. if (endIndex == -1) {
20. resultArr[i] = tempStr.substring(fromIndex);
21. break;
22. }
23. resultArr[i] = tempStr.substring(fromIndex, endIndex);
24. fromIndex = endIndex + 1;
25. }
26. return resultArr;
27. }
28. }
29.
30. //将字符串前面和后头的多余脱离符去除去。
31. private static String trim(String str, char splitChar) {
32. int beginIndex = 0, endIndex = str.length();
33. for (int i = 0; i < str.length(); i++) {
34. if (str.charAt(i) != splitChar) {
35. beginIndex = i;
36. break;
37. }
38. }
39. for (int i = str.length(); i > 0; i--) {
40. if (str.charAt(i - 1) != splitChar) {
41. endIndex = i;
42. break;
43. }
44. }
45. return str.substring(beginIndex, endIndex);
46. }
47.
48. //计较字符串中脱离符中个数
49. private static int getCharCount(String str, char splitChar) {
50. int count = 0;
51. for (int i = 0; i < str.length(); i++) {
52. if (str.charAt(i) == splitChar) {
53. count++;
54. }
55. }
56. return count;
57. }
58. }
除对外API string2Array()外,类中还包括了两个支持要领。trim()认真将字符前导和尾部的多余脱离符删除去(第31~46行);而getCharCount()要领获取字符中包括脱离符的数目,以获得方针字符串数组的巨细(第49~57行)。
