Vincent Tran
Vincent Tran

Reputation: 33

Trouble understanding arrays in Java

Can someone please explain why my for loop is getting an error about requiring an int but finding a double? I need my array to be a double, why does my method not work?

public class RingBuffer 
{
   private double[] EmptyBuffer;
   private int size;
   private int capacity;

     public RingBuffer(int capacity){
        EmptyBuffer = new double[capacity];


    }

    public int size(){
        int counter = 0; 
        for(int i: EmptyBuffer){
            if(EmptyBuffer[i] != null)
                counter++;
            }

        return counter;
    }

Upvotes: 1

Views: 151

Answers (3)

user425495
user425495

Reputation:

You are using the foreach loop incorrectly, try the following:

public class RingBuffer 
{
   private double[] EmptyBuffer;
   private int size;
   private int capacity;

     public RingBuffer(int capacity){
        EmptyBuffer = new double[capacity];


    }

    public int size(){
        int counter = 0; 
        for(double element : EmptyBuffer){
            if(element != 0) // Testing for null makes no sense! Test for non-zero?
                counter++;
            }

        return counter;
    }

Additionally, testing if a double is null or not makes no sense. Perhaps you should test if it is non-zero instead.

Upvotes: 3

scottb
scottb

Reputation: 10084

The semantics of the enhanced for loop ...

for (int i : EmptyBuffer) { ... }

are this: "for each integer element i in my array of doubles..."

As you can see, this makes no sense at all. You array is an array of doubles, and so you cannot iterate through each integer element that it contains.

Moreover, there is this syntax in your code snippet:

if(EmptyBuffer[i] != null)

Since EmptyBuffer is an array of doubles, it is an array of a primitive type, i.e. -not- a reference type. Because primitive types are not reference types, they may not be null and so it makes no sense to test the elements of your array for null.

Upvotes: 3

aaronman
aaronman

Reputation: 18750

 for(double i: EmptyBuffer){

The array is of doubles so the object needs to be a double. You could cast the double to an int if thats what you want

Upvotes: 5

Related Questions