简体   繁体   English

无法理解Java中的数组

[英]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? 有人可以解释一下为什么我的for循环为什么会出现一个错误,该错误要求输入int但找到一个double吗? I need my array to be a double, why does my method not work? 我需要数组为double,为什么我的方法不起作用?

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;
    }
 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 如果那是您想要的,则可以将double转换为int

The semantics of the enhanced for loop ... 增强的for循环的语义...

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, ie -not- a reference type. 由于EmptyBuffer是双精度数组,因此它是原始类型(即非引用类型)的数组。 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. 因为原始类型不是引用类型,所以它们可能不能为null,因此没有必要测试数组的元素是否为null。

You are using the foreach loop incorrectly, try the following: 您错误地使用了foreach循环,请尝试以下操作:

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. 此外,测试double是否为null毫无意义。 Perhaps you should test if it is non-zero instead. 也许您应该测试它是否非零。

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

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