java 将值添加到double[] arraylist

bvk5enib  于 2023-03-28  发布在  Java
关注(0)|答案(4)|浏览(170)

我有以下数组

ArrayList<double[]> db_results = new ArrayList<double[]>();

我想加上这样的值

db_results.add(new double[] {0,1,2});

但在这样的循环中

for ( int i = 0 ; i <= 2; i++) {
    double val = Double.parseDouble(i);
    db_results.add(new double[] {val});
}

很明显,这是每次添加一个新数组,只有一个值...那么我如何让它将所有值添加到一个数组中呢?

ctehm74n

ctehm74n1#

ArrayList<double[]> db_results = new ArrayList<double[]>();

double[] nums = new double[3];
for (int i = 0; i < nums.length; i++) {
  nums[i] = i;
}
db_results.add(nums);
goqiplq2

goqiplq22#

首先创建double[],向其添加数字,然后将该数组添加到List
(The变量应该声明为List,顺便说一句,而不是ArrayList,除非你特别将它传递给显式需要ArrayList的东西。

afdcj2ne

afdcj2ne3#

就像这样:

max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
    {
     double val = Double.parseDouble(i);
     doubles[i] = val;
    }
db_results.add(doubles);
5m1hhzi4

5m1hhzi44#

import java.util.Scanner;
class DarrayEx2
{
    public static void main(String args[])
      {
       int a[][]=new int[3][3];
       int r,c,sumr;
       Scanner s=new Scanner(System.in);
        for(r=0;r<a.length;r++)
         {
           for (c=0;c<a.length ;c++ )
            {
             System.out.println("enter an  element");
             a[r][c]=s.nextInt();
            }
          }
          for(r=0;r<a.length;r++)
            {
              sumr=0;
              System.out.println("elements in a["+r+"] row is");
               for (c=0;c<a[1].length ;c++ )
                 {
                   System.out.println(" "+a[r][c]);
                   sumr = sumr+a[r][c];
                 }

               System.out.println(" = "+sumr);
               System.out.println("  ");
             }
         }
}

来源:http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm

相关问题