20175204 张湲祯 2018-2019-2《Java程序设计》
Arrays和String单元测试
一.类的作用
1.- String类
charAt
String的charAt的作用是将字符串中第i个位置上的字符(从0开始计数)赋值给n,其用法为n=string.charAt(i)
split
String的split的作用是将字符串拆分成为几个字符串,其用法为(将字符串string以:为界限进行拆分,将拆分的几个字符串赋值给字符串数组string1)string1=string.split(":")
2.- Arrays类
sort
Arrays的sort的作用是将数组中的元素从小到大排序,其用法为(对arr数组进行排序)Arrays.sort(arr);
binarySearch
Arrays的binarySearch是寻找数组中某个元素所处的位置,其用法为(在arr中寻找数字1,将数字1的位置赋值给n,从0开始计数)n=Arrays.binarySearch(arr,1);
二.相关代码
测试代码
import junit.framework.TestCase;
import org.junit.Test;
import java.lang.*;
import java.util.Arrays;
public class ComplexTest extends TestCase {
String str = "zyz is xinzhou huge";
String str2 = "zyz:is:xin:zhou:hu:ge";
String[] str3 = new String[]{ "1", "7", "5", "2", "0", "4"};
double str4[] = {2.0, 1.7, 5.2, 0.4, 66.6};
@Test public void testcharAt() throws Exception {
assertEquals('z', Complex.getcharAt(str,0));
assertEquals('y', Complex.getcharAt(str,1));
assertEquals('z', Complex.getcharAt(str,2));
assertEquals('h', Complex.getcharAt(str,15));
assertEquals('g', Complex.getcharAt(str,17));
}
@Test public void testsplit() throws Exception {
assertEquals("zyz", Complex.getsplit(str2)[0]);
assertEquals("hu", Complex.getsplit(str2)[4]);
assertEquals("ge", Complex.getsplit(str2)[5]);
}
@Test public void testgetsort() throws Exception {
//ArraysTest(str3);
assertEquals("5", Complex.getsort(str3)[4]);
assertEquals("2", Complex.getsort(str3)[2]);
assertEquals("0", Complex.getsort(str3)[0]);
assertEquals("4", Complex.getsort(str3)[3]);
}
@Test
public void testgetbinarySearch() throws Exception {
//ArraysTest2(str4);
assertEquals(2, Arrays.binarySearch(Complex.getbinarySearch(str4), 2.0));
assertEquals(0, Arrays.binarySearch(Complex.getbinarySearch(str4), 0.4));
assertEquals(4, Arrays.binarySearch(Complex.getbinarySearch(str4), 66.6));
}
}
import java.util.Arrays;
public class Complex{
//测试charAt
public static char charAt(String str, int i) {
return str.charAt(i);
}
public static char getcharAt(String str, int i) {
return charAt(str, i);
}
//测试split
public static String[] split(String str) {
String[] strsort = str.split(":");
return strsort;
}
public static String[] getsplit(String str) {
return split(str);
}
//测试sort
public static String[] sort(String[] str3) {
Arrays.sort(str3);
return str3;
}
public static String[] getsort(String[] str3) {
return sort(str3);
}
//测试binarySearch
public static double[] binarySearch(double[] str4) {
Arrays.sort(str4);
return str4;
}
public static double[] getbinarySearch(double[] str4) {
return binarySearch(str4);
}
}