java 减去两个 Long 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42147062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:24:20  来源:igfitidea点击:

Subtracting two Long values

javasubtraction

提问by Me123

Why do I get error when I run the code below? How can I fix this? I want to System.out.print(hi-hello);

为什么我在运行下面的代码时会出错?我怎样才能解决这个问题?我想要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);
    }
}

采纳答案by ΦXoc? ? Пepeúpa ツ

Because hiand loware declared as LONGobjects, they must be either declared as literal by adding the L at the end or use the Long class

因为hilow被声明为LONG对象,所以它们必须要么通过在末尾添加 L 来声明为文字,要么使用 Long 类

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

回答by YCF_L

Your attribute declaration and init should be inside your class :

你的属性声明和 init 应该在你的类中:

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

Not out side for that you don't get correct result :

不是因为你没有得到正确的结果:

and your Long is not correct format it should be like this :

并且您的 Long 格式不正确,它应该是这样的:

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

And when you are calling your attribute in a static method then you should to make them static, so your program should look like this :

当您在静态方法中调用您的属性时,您应该将它们设为静态,因此您的程序应如下所示:

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

This will print:

这将打印:

3480

NOTE

笔记

Like @EJP said in the comment :

就像@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;

当一个数字太大而无法用 int 表示时,必须通过添加 L 将其显式声明为 long:

long n = 9876543210L;

回答by Yiheng Jiang

longsdoes not use normal operators like +or -, instead, you need to use Long.sum(long l1, l2).

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

I'm not sure if there's other ways to do it, but this is what I use.

我不确定是否还有其他方法可以做到,但这就是我使用的方法。