我对为什么 index
的值在这里没有增加有一些疑问。
我这样声明数组的原因是因为我需要存储 n
个自然数,其中 (1 ≤ n ≤ 1012),所以数字很大这就是为什么我采用了 long
类型的数组,但随后出现错误,指出我无法在组中放入任何 long
值,这就是为什么我将其转换为int
。有没有办法为这种类型的条件声明一个数组,因为我想要大量的索引,并且我不能在 [ ]
中放入很长的数字。
希望大家理解我的问题
代码:
import java.util.Scanner;
class Error{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long array[] = new long[(int) n];
long index = 0;
for (int j = 1; j <= n; j++) {
if (j % 2 != 0) {//odd
array[(int) index++] = j;
System.out.print(" " + array[(int) --index]);
System.out.print(index);// index value -> always 0 why??
System.out.print(j);
}
}
System.out.println();
}
}
输出:
Unix-Box ~/Desktop$ javac Error.java
Unix-Box ~/Desktop$ java Error
10
101 303 505 707 909
Unix-Box ~/Desktop$
中间值为index
,并且始终为0
我喊的是什么样的
10
101 313 525 737 949
Unix-Box ~/Desktop$
最佳答案
根据 https://www.quora.com/What-is-the-maximum-size-of-the-array-in-Java , 理论上,数组的最大大小是 2147483647,但实际上,为了安全起见,我们希望使用 2147483600。将数组声明为 long 类型意味着可以在其中存储 long 值。也许您可以使用二维数组来存储很长的 n 个值。类似的东西——
public static void main(String[] args)
{
System.out.println("enter the size of the array:");
Scanner in = new Scanner(System.in);
long n = Long.parseLong(in.nextLine());
int secondIndex = 2147483600;
int firstIndex = ((int)(n/secondIndex))+1;
if(secondIndex > n)
{secondIndex = (int)n;
}
else{int leftover = (int)(n%secondIndex);
secondIndex = secondIndex - leftover;}
long[][] array = new long[firstIndex][secondIndex];
//loop through array
outerloop:
for(int i =0;i <firstIndex; i++)
{
for(int z = 0; z<secondIndex; z++)
{
System.out.println("do work with number here: " + array[i][z]);
if(z==(secondIndex-1))
{
z=0;
continue outerloop;
}
}
}
}
您可能会遇到 java.lang.OutOfMemoryError:,可以通过阅读本文 https://plumbr.eu/outofmemoryerror/java-heap-space 来解决该错误.
关于java - 数组索引不递增(需要在方括号中进行转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728727/