我已经将一个变量定义为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), };
}
}
答案 0 :(得分:15)
对于被视为长号的数字,您需要L
后缀:
new Applicant("Bill Gates", 850, 3710000000L, 500000)
如果缺少L
后缀,编译器会将文字视为int
。
答案 1 :(得分:5)
您需要通过附加L
new Applicant("Bill Gates", 850, 3710000000L, 500000),
来自JLS
如果整数文字后缀为ASCII字母L或l(ell),则其长度为long;否则它是int
类型
答案 2 :(得分:2)
将3710000000更改为3710000000L。问题是如果没有L
,Java会将其视为int
。