1

我已将一个变量定义为 long,当我尝试将其用作数组中的一个时,它不断抛出一个错误,指出我的值超出了 int 范围。好吧,不开玩笑,它很长,我把它定义为一个。

下面是我的代码。在第二个类 LoanOfficer 中,您会发现第二个申请人比尔·盖茨(Bill Gates),其年收入为 3,710,000,000,正在抛出错误。

public class Applicant {
    private String name;
    private int creditScore;
    private long annualIncome;
    private int downPayment;
    private boolean status;

    public Applicant(String name, int creditScore, long annualIncome,
            int downPayment) {
        this.name = name;
        this.creditScore = creditScore;
        this.annualIncome = annualIncome;
        this.downPayment = downPayment;
        this.status = false;
    }

    public String getName() {
        return name;
    }

    public int getCreditScore() {
        return creditScore;
    }

    public long getAnnualIncome() {
        return annualIncome;
    }

    public int getDownPayment() {
        return downPayment;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public boolean isStatus() {
        return status;
    }
}

public class LoanOfficer {
    public static void main(String[] args) {
        Applicant[] applicants = {
                new Applicant("MC Hammer", 400, 25000, 5000),
                new Applicant("Bill Gates", 850, 3710000000, 500000),
                new Applicant("MC Hammer", 400, 25000, 5000),
                new Applicant("MC Hammer", 400, 25000, 5000), };
    }
}
4

3 回答 3

15

您需要L被视为 long 的数字的后缀:

new Applicant("Bill Gates", 850, 3710000000L, 500000)

如果L缺少后缀,编译器会将文字视为int.

于 2013-04-08T19:20:37.173 回答
5

您需要通过附加以下内容将 3710000000 指定为长文字L

new Applicant("Bill Gates", 850, 3710000000L, 500000),

来自JLS

如果整数文字以 ASCII 字母 L 或 l (ell) 为后缀,则它是 long 类型;否则它是 int 类型

于 2013-04-08T19:20:36.530 回答
2

将 3710000000 更改为 3710000000L。问题是,如果没有L,Java 会将其视为int.

于 2013-04-08T19:21:51.320 回答