《Java程序设计》第12周课堂实践总结
实践一 教材代码检查-p98
要求
修改教材P98 Score2.java, 让执行结果数组填充是自己的学号;
提交在IDEA或命令行中运行结查截图,加上学号水印,没学号的不给成绩
代码
import java.util.Arrays;
public class Score2 {
public static void main(String[] args) {
int[] scores=new int[10];
for(int score:scores){
System.out.printf("%2d",score);
}
System.out.println();
Arrays.fill(scores,20155314);
for(int score:scores){
System.out.printf("%3d ",score);
}
}
}
运行结果截图
实践二 Arrays和String单元测试
要求
在IDEA中以TDD的方式对String类和Arrays类进行学习
测试相关方法的正常,错误和边界情况
- String类
- charAt
- split
- Arrays类
- sort
binarySearch
提交运行结果截图和码云代码链接,截图没有水印的需要单独找老师验收才有成绩
代码
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Test20155314 {
@Test
public void testString() {
String s ="abc";
assertEquals('b',s.charAt(1));
}
}
运行结果截图
实践三 MySort
要求
模拟实现Linux下Sort -t : -k 2的功能。
参考 Sort的实现。提交码云链接和代码运行截图。
1 import java.util.*; 2 3 public class MySort1 { 4 public static void main(String [] args) { 5 String [] toSort = {"aaa:10:1:1", 6 "ccc:30:3:4", 7 "bbb:50:4:5", 8 "ddd:20:5:3", 9 "eee:40:2:20"}; 10 11 System.out.println("Before sort:"); 12 for (String str: toSort) 13 System.out.println(str); 14 15 Arrays.sort(toSort); 16 17 System.out.println("After sort:"); 18 for( String str : toSort) 19 System.out.println(str); 20 } 21 }
代码
import java.util.*;
public class Mysort20155314 {
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"};
/*****************以下为添加内容********************/
String[] tmp=new String[toSort.length];
for(int i=0;i<toSort.length;i++)
{
String list[]=toSort[i].split(":");
tmp[i]=list[3];
}
/**************************************************/
System.out.println("Before sort:");
for (String str : toSort)
System.out.println(str);
Arrays.sort(tmp);
/*****************以下为添加内容********************/
String []t=new String[toSort.length];
for(int i=0;i<toSort.length;i++)
for(int j=0;j<toSort.length;j++)
if(toSort[j].charAt(9)==(tmp[i].toCharArray()[0]))
t[i]=toSort[j];
/**************************************************/
System.out.println("After sort:");
for (String str : t)
System.out.println(str);
}
}