我在这一行中收到“不兼容的类型:可能会丢失从 long 到 int 的转换”异常: boolean arr[] = new boolean [limit];我不明白为什么会发生这种情况,因为我将输入值存储为 long,它是如何转换为 int 的?
import java.util.*;
import java.io.*;
public class PrimeSieve
{
public static void main (String args [])
{
//getting the number
Scanner x = new Scanner (System.in);
System.out.println("What is your number?");
long limit = x.nextLong();
long count = 0;
//making all the numbers upto the given number prime
boolean arr[] = new boolean [limit];
for ( long i = 2; i <=Math.sqrt(limit); i++)
{
arr[i] = true;
}
最佳答案
这是因为您使用 long
作为数组的大小。
Java 支持数组达到一定限制,该限制约为 Integer.MAX_VALUE - x
(请参阅 this),因此不允许使用 long 来指定大小。
引自JLS:
Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.
关于java - 从 long 到 int 的可能有损转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31144675/