可能有损从长期转换为int [英] Possibly lossy conversion from long to int

查看:120
本文介绍了可能有损从长期转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这行中得到不兼容的类型:可能从long到int的转换异常:boolean arr [] = new boolean [limit];我不明白为什么会发生这种情况,因为我将输入值存储在很长的时间内,如何转换成int?

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;
   }


推荐答案

long 作为数组的大小。

Java支持数组达到一定的限制,大约在 Integer.MAX_VALUE - x (请参阅)所以使用长时间来指定大小是不允许的。

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.

从JLS引用:


数组必须由int值索引...尝试访问具有较长索引值的数组组件导致编译时错误。

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.

这篇关于可能有损从长期转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆