user1730056
user1730056

Reputation: 623

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. My problem is that I'm unable to add/append to the result list.

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

Upvotes: 0

Views: 202

Answers (2)

giorashc
giorashc

Reputation: 13713

Your list is actually an array (double[]), which is NOT an object with the method 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 (e.g an ArrayList) and then you can actually use the add method:

 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)

Upvotes: 3

Miljen Mikic
Miljen Mikic

Reputation: 15241

There's no method add for arrays in Java. You should declare list as:

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

Upvotes: 0

Related Questions