[英]Trouble understanding arrays in Java
有人可以解釋一下為什么我的for循環為什么會出現一個錯誤,該錯誤要求輸入int但找到一個double嗎? 我需要數組為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){
該數組是雙精度型,因此對象必須是雙精度型。 如果那是您想要的,則可以將double轉換為int
增強的for循環的語義...
for (int i : EmptyBuffer) { ... }
是這樣的:“對於我雙打數組中的每個整數元素……”
如您所見,這根本沒有任何意義。 您的數組是一個雙精度數組,因此您無法遍歷它包含的每個整數元素。
此外,您的代碼段中包含以下語法:
if(EmptyBuffer[i] != null)
由於EmptyBuffer是雙精度數組,因此它是原始類型(即非引用類型)的數組。 因為原始類型不是引用類型,所以它們可能不能為null,因此沒有必要測試數組的元素是否為null。
您錯誤地使用了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;
}
此外,測試double是否為null毫無意義。 也許您應該測試它是否非零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.