简体   繁体   English

向数组添加/追加元素-Java

[英]Adding/Appending elements to an array - Java

I am building a method which takes as argument, an array of decimal numbers, and a decimal threshold. 我正在建立一个以参数,十进制数字数组和十进制阈值为参数的方法。 The method should output all numbers from the list that are greater than the threshold. 该方法应输出列表中大于阈值的所有数字。

My plan is to execute a for loop and examine each number in the array, and if that number (i) is greater than the threshold (x), to append to my result list. 我的计划是执行一个for循环并检查数组中的每个数字,如果该数字(i)大于阈值(x),则追加到我的结果列表中。 My problem is that I'm unable to add/append to the result list. 我的问题是我无法添加/添加到结果列表。

I have System.out.println("Nothing here"); 我有System.out.println("Nothing here"); just to help me see if it's actually going through the for loop or not, but my IDE is saying that calling list.add(a[i]); 只是为了帮助我看看它是否实际上正在通过for循环,但是我的IDE却在说调用list.add(a[i]); is wrong. 是错的。 I am a beginning programmer and not sure on how to fix this. 我是一个初级程序员,不确定如何解决此问题。 Here is my code: 这是我的代码:

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");
            }
    }
}

Your list is actually an array ( double[] ), which is NOT an object with the method add . 您的列表实际上是一个数组( double[] ),它不是使用add方法的对象。 You should treat it as a regular array (which in your case between, you have initialized to be an empty array, which means you can't set any elements in it). 您应该将其视为常规数组(在您之间的情况下,您已初始化为空数组,这意味着您无法在其中设置任何元素)。

What you should do is use an actual implementation of Lis instead (eg an ArrayList ) and then you can actually use the add method: 您应该做的是使用Lis的实际实现代替(例如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");
      }
 }

Notice also that you had the number '22' hard coded (you should use x ) 还要注意,您已对数字“ 22”进行了硬编码(应使用x

There's no method add for arrays in Java. Java中没有为数组add方法的方法。 You should declare list as: 您应将清单声明为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM