英文:
Java converts long to int
问题
以下是要翻译的代码部分:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long N = s.nextLong();
long[] arr = new long[N];
System.out.println(N);
}
}
获取到以下错误信息:
HelloWorld.java:12: error: incompatible types: possible lossy conversion from long to int long[] arr = new long[N];
根据我理解,代码中没有涉及到int类型,有人能解释为什么会出现这个错误以及如何解决这个问题吗?
英文:
The following code:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner s = new Scanner(System.in);
long N = s.nextLong();
long[] arr = new long[N];
System.out.println(N);
}
}
Getting this error:
HelloWorld.java:12: error: incompatible types: possible lossy conversion from long to int long[] arr = new long[N];
As far as I understand there is no int involved in the code, can anyone explain why this is happening and how to solve this issue?
答案1
得分: 3
在Java中,数组的大小不能超过int的范围,因此数组创建的大小参数隐式地是一个int。将N改为一个int。
来自JLS 15.10.1数组创建表达式(重点在于):
每个维度表达式都会经历一次一元数值提升(§5.6.1)。提升的类型必须是
int,否则会导致编译时错误。
英文:
The size of arrays in Java can not exceed the range of an int, so the size parameter for array creation is implicitly an int. Change N to an int.
From JLS 15.10.1 Array Creation Expression (emphasis mine):
> Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.
答案2
得分: 2
Array subscripts and sizes in Java must always be int, so in this expression new long[N] the N is converted to int, and because long has a wider range than int, it's a narrowing conversion which must be done explicitly: new long[(int) N]. Or just read N as int: int N = s.nextInt().
英文:
Array subscripts and sizes in Java must always be int, so in this expression new long[N] the N is converted to int, and because long has wider range than int, it's a narrowing conversion which must be done explicitly: new long[(int) N]. Or just read N as int: int N = s.nextInt().
答案3
得分: 1
在这一行中,你正在创建一个大小为N的数组,但在Java中,数组的大小只能是整数,这就是为什么它将N视为一个整数。如果你的意图是创建一个大小为N的数组,你应该将N读取为一个整数。
int N = s.nextInt();
英文:
long[] arr = new long[N];
In this line you are creating an array of size N, but array sizes in Java can only be integers, that's why it's reading N as an int, if your intent is creating an array of N size you should read N as an int
int N = s.nextInt();
答案4
得分: 0
在Java中,数组的最大长度是2,147,483,647(2^31 - 1),这是int的最大长度。因此,数组最大可以容纳int的最大值,无法接受长整型数。
英文:
The maximum length of an array in java is 2,147,483,647 (2^31 - 1) which is the maximum length of int. So implicitly an array can have maximum the value of an int. So it cannot accept a long number.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论