减去两个 Long 值
Subtracting two Long values
为什么当我 运行 下面的代码时会出现错误?我怎样才能解决这个问题?我要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);
}
}
你的属性声明和初始化应该在你的 class :
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;
因为 hi 和 low 被声明为 LONG 对象,它们必须被声明通过在末尾添加 L 或使用 Long class
作为文字
public class HelloWorld {
public static void main(String[] args) {
Long hello = 43L;
Long hi = 3523L;
System.out.print(hi-hello);
}
}
longs 不使用 + 或 - 等普通运算符,相反,您需要使用 Long.sum(long l1, l2)
.
我不确定是否有其他方法可以做到这一点,但这是我使用的。
为什么当我 运行 下面的代码时会出现错误?我怎样才能解决这个问题?我要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);
}
}
你的属性声明和初始化应该在你的 class :
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;
因为 hi 和 low 被声明为 LONG 对象,它们必须被声明通过在末尾添加 L 或使用 Long class
作为文字public class HelloWorld {
public static void main(String[] args) {
Long hello = 43L;
Long hi = 3523L;
System.out.print(hi-hello);
}
}
longs 不使用 + 或 - 等普通运算符,相反,您需要使用 Long.sum(long l1, l2)
.
我不确定是否有其他方法可以做到这一点,但这是我使用的。