长期在Java中被视为数组中的int

Chr*_*ald 2 java arrays int long-integer

我已经将变量定义为long,当我尝试将其用作数组中的一个变量时,它会继续抛出一个错误,说我的值超出了int范围.嗯,不开玩笑,这很长,我把它定义为一个.

以下是我的代码.在第二课,LoanOfficer,你会发现第二个申请人比尔盖茨,其年收入为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), };
    }
}
Run Code Online (Sandbox Code Playgroud)

gpa*_*ani 15

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

new Applicant("Bill Gates", 850, 3710000000L, 500000)
Run Code Online (Sandbox Code Playgroud)

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

  • @ user2217408为了使这个问题的主要答案,接受它! (2认同)

Rei*_*eus 5

您需要通过附加指定3710000000作为长文字L:

new Applicant("Bill Gates", 850, 3710000000L, 500000),
Run Code Online (Sandbox Code Playgroud)

来自JLS

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