2009-10-23 52 views
0

任何人都可以告訴我爲什麼我的最後一個返回語句不起作用嗎?返回聲明錯誤 - 解析IP地址字符串

public class IpAddress 
{ 
    private String dottedDecimal; 
    private int[] Octet= new int[4]; 
    public int i; 

    //Default constructor 
    public IpAddress() 
    { 
     dottedDecimal = "0.0.0.0"; 
     for (i=0; i<=3; i++) 
     { 
      Octet[i] = 0; //setting the array to zero 
     } 
    } // end default constructor 

    //************************************ 
    //Specified constructor 
    public IpAddress(String myAddress) 
    { 
     dottedDecimal = myAddress; 
     String[] parsedOctets; 
     parsedOctets = myAddress.split("\\Q.\\E"); // allows to stop at the dot 
     for (i=0; i <=3; i++) 
     { 
      Octet[i] = Integer.parseInt(parsedOctets[i]); // breaking the string down to integers 
     } 
    }// end specified constructor 

    //***************************************************** 
    public String getDottedDecimal() 
    { 
     return dottedDecimal; 
    } 

    //********************* 
    public int getOctet() 
    { 
     for (this.i=0; this.i <=3; this.i++) 
     { 
      return this.Octet[i]; 
     } 
    } 

} // end ip address class 
+0

你是什麼意思「las return statement」?請提供更多詳細信息... – 2009-10-23 01:15:29

+0

不要忘記單擊複選標記以接受答案... – 2009-10-23 02:29:07

+0

Bob Kaufman已發佈解決方案。但我想我會評論一下事情。 「我」不應該是一個實例變量。應該使用實例變量來存儲對象的狀態。我是一個用於迭代方法的計數器。它與對象本身無關。相反,你應該這樣做:「for(int i = 0; i <= 3; i ++){...}」。 這種方式很明顯,「我」是專門爲迭代for循環而創建的。不,它不需要更多的資源。事實上,它需要少得多。 – 2009-10-23 12:13:16

回答

3

我想你想要的是最後的方法是這樣的:

public int getOctet(int which) 
{ 
    if (which >= 0 && which <= 3) 
     return this.Octet[ which ]; 
    else 
     return -1; // error. Consider throwing an exception 
} 
+0

這就是我在找的東西我想我明白你在說什麼,你在這個聲明中說0到3是可以接受的,因爲我只有這個數組中的對象,但是其他的東西都是負數,因爲它是錯誤的。我剛剛瞭解到這個parseint的東西,以及你們都很棒。 – daddycardona 2009-10-23 01:33:13

4

看起來像功課給我,但是這顯然是行不通的:

public int getOctet() 
{ 
    for (this.i=0; this.i <=3; this.i++) 
    { 
     return this.Octet[i]; 
    } 

} 

將從函數的第一個迭代之後返回,你不能從一個函數多次返回。

+1

在某些情況下,如果返回類型是IEnumerable,你可以做一個收益回報 – 2009-10-23 01:33:08

+0

嗯,是的,但這不是這種情況。 – 2009-10-23 03:55:11

0

對於你的最後一條語句,你正在運行一個什麼也不做,只返回一個值的循環。它會在第一次返回,但是循環停止運行,所以其他返回不做任何事情。

public int getOctet() 
{ 
    for (this.i=0; this.i <=3; this.i++) 
     { 
      return this.Octet[i]; 
     } 

} 

這相當於:

  return this.Octet[0]; 

因爲它只能運行一次。

0

如果你指的是「獲得八位」功能,它僅會返回Octet[0];

return語句停止第一次被擊中的函數的執行。你真正想要的是:

public int[] getOctet() 
{ 
      return this.Octet; 
} 
+0

這不起作用我試過我認爲這是因爲我正在尋找一個數組。哦拉非常好,我很欣賞它。 – daddycardona 2009-10-23 01:34:02

0

通過命名你的方法getOctect(),似乎你希望返回數組,不來自數組中的單個int。在這種情況下,您應該將其簡化爲如下所示:

public int[] getOctet() 
{ 
     return this.Octet; 

}