在Android studio中,测试输出数组中最大子数组的和

首先在gredle文件中加入

defaultConfig {
        applicationId "com.example.app2"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"

    }
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.0'
}

创建Java Class类 Array,编写输出数组中子数组最大值的和的代码

public class Array {
    public int maxSum(int[] array) {

        if (array == null || array.length == 0) {
            throw new IllegalArgumentException("array is null or empty.");
        }

        int result = array[0], mark = 0;

        for (int i = 0; i < array.length; i++) {
            int element = array[i];

            if (mark >= 0) {
                mark += element;
            } else {
                mark = element;
            }

            if (mark > result) {
                result = mark;
            }
        }

        return result;
    }

}

创建测试类(选中Array右击选择Go to >Test),并编写代码

package com.example.app2;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by Tony on 2017/3/17.
 */
public class ArrayTest {
  private Array array;
    int sum []={1, -2, 3, 10, -4, 7, 2, -5};
    @Before
    public void setUp() throws Exception {
      array =new Array();
    }

    @Test
    public void testMaxSum() throws Exception {
        assertEquals(18d,array.maxSum(sum),0);
    }
}

最后选中ArrayTest右击选择Run'ArrayTest',运行结果:

原文地址:https://www.cnblogs.com/krylova/p/6567872.html