Calculate
package jsx2; import java.util.Scanner; public class Calculate { public static void main(String[] args){ Calculate i =new Calculate(); int Max = 0; int Max1 = 0; Scanner in=new Scanner(System.in); System.out.print("请输入数组的长度:"); int j=in.nextInt(); System.out.print("请依次输入数组:"); int Arr[]=new int[j]; for(int a = 0;a < j; a++){ Arr[a]=in.nextInt(); } int Arr1[]=new int [j]; for(int a = 0; a < j; a++) { for(int b = 0; b < j; b++){ Arr1[b]=Arr[(b + a)%(j)]; } Max=i.findMaxArr(Arr1); if(Max > Max1) { Max1 = Max; } } System.out.print("最大的子数组和为"+Max1); } public int findMaxArr(int[] arr) { int Arr = 0; int MaxArr = 0; int c = arr.length; int Location1=0; int Location2=0; int a; for ( a = 0; a < c; a++) { Arr += arr[a]; if (Arr < 0) { Arr = 0; } if (Arr > MaxArr) { MaxArr = Arr; } } for(a = Location2; a >= 0; a--) { if(MaxArr-arr[a]==0) { Location1 = a; break; } } if (MaxArr == 0) { for ( a = 0; a < c; a++) { if (a == 0) { MaxArr = arr[a]; } if (arr[a] > MaxArr) { MaxArr = arr[a]; } } } return MaxArr; } }
CalculateTest
package jsx2; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class CalculateTest { private Calculate mcalculate; int[] Calculate = {-5,4,10,3,8}; @Before public void setUp() throws Exception { mcalculate =new Calculate(); } @Test public void testMain() throws Exception { } @Test public void testFindMaxArr() throws Exception { assertEquals(3, mcalculate.findMaxArr(Calculate), 0);
测试结果