为什么“断言”不能按照我想要的方式在这段代码中工作?

时间:2013-01-10 16:54:35

标签: java

为什么构造函数中的assert语句在以下代码中不起作用? (我想用它而不是if语句,我已经注释掉了)

import java.util.HashMap;
import java.util.Map;


enum Suite{
    HEARTS, DIAMONDS, SPADES,CLUBS;
}

public class Card {
    private Suite suite;
    private int number;
    private String name;

    public Card(int number, Suite suite) {
//      if(number < 0 || number > 13)
//          throw new IllegalArgumentException(); 
        assert(!(number < 0 || number >13));

        this.number=number;
        this.suite=suite;
        initialize();

    }
    private void initialize(){
        switch(number){
        case 1: name="Ace"; break;
        case 2: name="Two"; break;
        case 3: name="Three"; break;
        case 4: name="Four"; break;
        case 5: name="Five"; break;
        case 6: name="Six"; break;
        case 7: name ="Seven"; break;
        case 8: name ="Eight"; break;
        case 9: name="Nine"; break;
        case 10: name="Ten"; break;
        case 11: name="Jack"; break;
        case 12: name="Queen"; break;
        case 13: name="King"; break;
        default: break;
        }
    }
    public int getNumber() {
        return number;
    }

    public int getBJNumber(){
        if(number == 11 || number == 12 || number == 13 )
            return 10;
        else
            return number;
    }

    public Suite getSuite() {
        return suite;
    }

    public String toString(){
        return name + " of " + suite.toString();
    }

    public static void main(String[] args) {
        Card testCard = new Card(1, Suite.CLUBS);
        System.out.println(testCard);
        Card testCard2 = new Card(5, Suite.CLUBS);
        System.out.println(testCard2);
        Card testCard3 = new Card(1, Suite.CLUBS);
        System.out.println(testCard3);
        Card testCard4 = new Card(15, Suite.CLUBS);
        System.out.println(testCard4);
    }
}

输出:

Ace of CLUBS
Five of CLUBS
Ace of CLUBS
null of CLUBS <---this should have not been shown.

也许我对断言的理解不正确?

2 个答案:

答案 0 :(得分:10)

默认情况下,assert已停用。您需要明确启用-ea标志。这是关于如何启用/禁用断言的java tutorial

答案 1 :(得分:2)

默认情况下断言是关闭的。你必须告诉vm来评估它们。

启用它们: -ea