在写程序的时候单元测试十分重要,下面是求数组最大值的代码实现和单元测试部分以及结果截屏
1 import java.util.Scanner; 2 public class Test { 3 public static void main(String[] args){ 4 int a[]={1,2,3,4,5,6}; 5 judge(Largest(a,6)); 6 int a2[]={9,4,0,2,5,10}; 7 judge(Largest(a2,6)); 8 int[] a3={000,-1,-88,3,000,999}; 9 judge(Largest(a3,6)); 10 int a4[]={}; 11 judge(Largest(a4,0)); 12 int[] a5=new int[5]; 13 judge(Largest(a5,5)); 14 while(1>0){ 15 System.out.println( " 请输入数组的长度"); 16 Scanner sc2=new Scanner(System.in); 17 int length=sc2.nextInt(); 18 int A[]=new int[length]; 19 System.out.println( "请输入一个数组"); 20 Scanner sc=new Scanner(System.in); 21 for(int i=0;i<length;i++) 22 { 23 A[i]=sc.nextInt(); 24 } 25 judge(Largest(A,length)); 26 } 27 } 28 public static int Largest(int list[],int length){ 29 if(list==null||length==0){ 30 return 0; 31 } 32 int i,max=list[0]; 33 for(i=0;i<length;i++){ 34 if(list[i]>max){ 35 max=list[i]; 36 } 37 } 38 System.out.print( " "+max); 39 return 1; 40 } 41 public static void judge(int i){ 42 if(i==0){ 43 System.out.print( " 数组为空!"); 44 } 45 else{ 46 System.out.print( "是最大值"); 47 } 48 } 49 }
可知在
这几个测试数组运行结果为: