编程语言
首页 > 编程语言> > 使用SBT管理构建时启用Java断言

使用SBT管理构建时启用Java断言

作者:互联网

一段时间以来,我第一次在Eclipse之外进行Java编程(针对Coursera算法课程),并且尝试使用SBT进行构建. SBT正常工作(虽然启动缓慢),但我不知道如何启用断言.以下两种似乎都不起作用.

javaOptions += "-ea" // doesn't work
javaOptions in run += "-ea" // doesn't work either

build.sbt

// disable using the Scala version in output paths and artifacts
crossPaths := false

// Enable assertions?
javaOptions += "-ea" // doesn't work
//javaOptions in run += "-ea" // doesn't work either

organization := "me"

name := "me"

version := "1.0-SNAPSHOT"

// Use jars from parent dir. Normally jars are stuck in lib/
unmanagedJars in Compile += file("../stdlib.jar")

unmanagedJars in Compile += file("../algs4.jar")

QuickFind.java

import java.util.Arrays; // I hate java so much

public class QuickFind {
    public int[] id;

    public QuickFind (int N) {
        id = new int[N];
        int i;
        for (i = 0; i < N; i++) {
            id[i] = i;
        }
    }

    public boolean connected (int p, int q) {
        return id[p] == id[q];
    }

    public void union (int p, int q) {
        // Walk through array and make everything with id = p || q
        // equal to id p
        int pid = id[p];
        int qid = id[q];

        int i;
        for (i = 0; i < id.length; i++) {
            if (id[i] == qid) id[i] = pid;
        }
    }

    public static void main (String[] args) {
        StdOut.println("QuickFind"); // from stdlib.jar
        QuickFind uf = new QuickFind(4);
        uf.union(0,1);

        // Assert unions work
        StdOut.println("array=" + Arrays.toString(uf.id));
        assert uf.connected(0,1);
        assert uf.connected(0,2); // <---------------------this should fail
    }
}

解决方法:

This link解释了这一点.简短版本是在build.sbt中使用以下内容:

// Enable assertions
fork in run := true

javaOptions in run += "-ea"

标签:sbt,assertions,java
来源: https://codeday.me/bug/20191031/1974646.html