Java Addition将错误视为空

时间:2018-04-18 16:26:15

标签: java math

我很抱歉打扰你这个可能很明显的问题的人,但编译器不会给我任何东西,除了:

Arithmetic.java:4: error: null: 146367789778966
        int myNumber = 3 + 146367789778966;
        ^                 
           1 error
  

代码

public class Arithmetic {
public static void main(String[] args) {

    int myNumber = 3 + 146367789778966;
    System.out.println(myNumber);

    }
}

如果有人能告诉我什么是错的,那就太棒了!

3 个答案:

答案 0 :(得分:4)

146367789778966太大,无法容纳int类型。

int可容纳的最大值为2,147,483,647,因此该值不适合int,您的代码会抛出错误。

您可以使用更大的数据类型,例如long

有关数据类型的更多信息: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

答案 1 :(得分:2)

int的最大值是2,147,483,647。 所以你的号码太大了。

答案 2 :(得分:1)

  • public class PersonLocation { private final Serializable id; private final String name; private final Location location; /** * Constructor leveraged by Jackson to de-serialize an incoming * PersonLocation instance represented in JSON. * * @param id The instance identity. * @param name The name of the person. * @param location The location of the person. **/ @JsonCreator public PersonLocation ( @JsonProperty("id") Object id, @JsonProperty("name") String name, @JsonProperty("location") Location location) { //This safety check and cast should be a static utility method. if (!id instanceof Serializable) { throw new IllegalArgumentException("Id must be a serializable type."); } this.id = (Serializable)id; this.name = name; this.location = location; } public Serializable getId () { return id; } public String getName () { return name; } public Location getLocation () { return location; } } 实际上是Integer.MAX_VALUE

  • 2147483647大于146367789778966,因此无法存储在Integer.MAX_VALUE类型

像IntelliJ这样的int会警告你:

IDE

您可以使用前Error:(10, 28) java: integer number too large: 146367789778966 // what IntelliJ gives me

BigInteger