2012-11-25 79 views
0

我正在构建一个方法,它采用参数,十进制数字数组和小数阈值。该方法应输出列表中大于阈值的所有数字。将元素添加到/添加到数组 - Java

我的计划是执行for循环并检查数组中的每个数字,如果该数字(i)大于阈值(x),则追加到我的结果列表中。我的问题是我无法添加/附加到结果列表。

我有System.out.println("Nothing here");只是为了帮助我看看它是否真的经历了for循环,但我的IDE是说,调用list.add(a[i]);是错误的。我是一个开始的程序员,不确定如何解决这个问题。这里是我的代码:

public class a10 { 

    public static void main(String[] args) { 
     double a[] = {42, 956, 3,4}; 
     threshold(a, 2); 
    } 

    public static void threshold(double[] a, double x){ 
     double list[] = {}; 

     for (double i:a){ 
      if (i<22){ 
       list.add(a[i]); 
      }else{ 
       System.out.println("Nothing here"); 
      } 
    } 
} 
+0

你知道一个数组是什么,列表是什么? – Juvanis

+0

你不能在list [](这是一个数组)上执行那种添加操作。要获得类似的功能,请使用ArrayList或Vector –

+0

您应该大写类名称。 – keyser

回答

3

你的名单实际上是一个数组(double[]),这是与方法add的对象。你应该把它看作一个常规数组(在你的情况中,你已经初始化为一个空数组,这意味着你不能在其中设置任何元素)。

你应该做的是使用一个实际的实施丽丝,而不是(例如ArrayList),然后你可以实际使用add方法:

List<Double> result = new ArrayList<Double>(); 
for (double i:a){ 
     if (i>x){ 
      list.add(a[i]); 
     }else{ 
      System.out.println("Nothing here"); 
     } 
} 

另请注意,你有数字“22”硬编码(您应该使用x

+0

有没有办法将我的列表a更改为数组? – user1730056

+0

'double [] doubleArray = result.toArray(new double [result.size()]);' – giorashc

0

对于Java中的数组,没有方法add。你应该声明如下列表:

List<Double> list = new ArrayList<Double>(); //or some other type of list