问题是:
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
我的代码:
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
错误是:
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
为什么这么说? 并且用户打印的数字两次!
最佳答案
a[i+1] = Math.pow(2,a[i]); // issue here
当i=a.length-1
时,i+1
为a.length
。所以这个数组中没有索引值匹配。
建议:
创建一个数组,长度为lenght= a.length+1
double powArray[] =new double[a.length+1];
现在
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
关于java - 循环切掉数组的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925488/