java - 循环切掉数组的一个元素

标签 java arrays

问题是:

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+1a.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/

相关文章:

java - 如何写入文本文件

java - 访问 Java 中的包

ruby - 为什么清除我的哈希值时也会清除我的哈希值数组?

javascript - 动态构建表达式以过滤 Javascript 数组

php - 在 PHP 中搜索给定数组的部分查询

java - 对可能包含数字的字符串进行排序

java - Spring Hibernate 悲观锁

java - Spring 启动: MVC not returning view : thymeleaf & Spring data

java - 检查数组中所有元素是否相等的最快方法

arrays - 在specflow中传递变量数组