问题
I am getting "incompatible types: possibly loss of conversion from long to int" exception in this line: boolean arr[] = new boolean [limit]; I don't understand why this is happening since I am storing the input value in long, how is it getting converted to 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;
}
回答1:
This because you are using a long as a size for an array.
Java supports array up to a certain limit which is around Integer.MAX_VALUE - x (see this) so using a long to specify the size is not allowed.
Quoting from 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.
回答2:
Array lengths and indices must always be ints. You cannot create an array with long length, nor can you refer to a long index in an array.
来源:https://stackoverflow.com/questions/31144675/possibly-lossy-conversion-from-long-to-int