1

为什么构造函数中的 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.

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

4

2 回答 2

10

默认情况下assert是禁用的。您需要明确启用使用-ea标志。这是有关如何启用/禁用断言的java教程。

于 2013-01-10T16:55:30.743 回答
2

断言默认是关闭的。你必须告诉虚拟机来评估它们。

启用它们: -ea

于 2013-01-10T16:55:53.413 回答