有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java减去两个长值

为什么我在运行下面的代码时会出错?我该怎么解决这个问题?我想System.out.print(hi-hello);

Long hello = 43;
Long hi = 3523;
public class HelloWorld{
    public static void main(String[] args){
        System.out.print(hi-hello);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    long不使用像+-这样的普通运算符,而是需要使用Long.sum(long l1, l2)

    我不确定是否还有其他方法,但这就是我使用的方法

  2. # 2 楼答案

    属性声明和初始化应该在类中:

    public class HelloWorld{
        Long hello = 43;
        Long hi = 3523;
    

    如果你得不到正确的结果,那就不要站在一边:

    你的Long格式不正确,应该是这样的:

      Long hello = 43L;
      Long hi = 3523L;
    

    当你在静态方法中调用属性时,你应该让它们成为静态的,所以你的程序应该是这样的:

    public class HelloWorld
    {
      static Long hello = 43L;
      static Long hi = 3523L;
      public static void main(String[] args)
      {
        System.out.print(hi-hello);
      }
    }
    

    这将打印:

    3480
    

    注意

    就像@EJP在评论中说的:

    When a number is too large to be represented by an int, it must be explicitly declared as a long by adding an L:

    long n = 9876543210L;
    
  3. # 3 楼答案

    由于hilow被声明为LONG对象,因此必须通过在末尾添加L或使用LONG类将它们声明为literal

    public class HelloWorld {
         public static void main(String[] args) {
            Long hello = 43L;
            Long hi = 3523L;
            System.out.print(hi-hello);
         }
    }