2013-06-24 19 views
1

我剛開始學習Java和我,直到達到陣列,我在「與」替代空間「準備這個節目(從一本書)。」 (點),我不能夠理解這個特定的行(它不是在書裏我從學習甚至提到)。請在我的Java代碼中解釋這個特定的行嗎?

請幫我一把。

class SpaceRemover{ 
    public static void main(String[] args){ 
     String mostFamous = "Hey there stackoverFLow  "; 
     char [] mf1 = mostFamous.toCharArray(); 
     for(int dex = 0; dex<mf1.length;dex++) 
     { 
      char current = mf1[dex]; // What is happening in this line ?? 
      if (current != ' ') { 
       System.out.print(current); 

      } 
      else{ 
       System.out.print('.'); 

      } 
     } 
     System.out.println(); 


     } 
    } 

有人請解釋什麼是發生 「焦電流= MF1 [DEX]。」

非常感謝您的時間。

+0

這些將有助於理解它:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays .html – 2013-06-24 06:43:13

回答

1

基本上java中的一個字符串是一個字符數組。那麼上面的代碼所做的就是將字符串轉換爲一個字符數組,以便以後可以訪問數組中的每個索引。然後代碼進入for循環,以遍歷char數組的所有indecies。

假設這已經很清楚,代碼現在創建一個char變量,它保存數組的當前索引。

char current = mf1[dex]; 

mf1是表示字符串的char數組。 dex是由for循環確定的char的當前索引。所以通過這樣做,我們可以檢查char數組的每個字符(字母)。現在,如果char「current」是空格,我們可以用點替換它。

+0

非常感謝真的很好的解釋。我寫下了你的答案......這讓我明白這個概念真的很棒。謝謝 :) – yeahhhhRIGHT

0

它將數組中的索引idx中的字符獲取並將其值存儲在current變量中。

0

的for循環是通過迭代字符字符串mostFamous字符。

你問行是獲得在特定位置的字符。功能類似於JavaScript的charAt(i)

2

你所得到的字符數組mf1(因此mf1[dex])內的第dex字符/項,並將其存儲到局部變量current

+0

感謝所有的答案:) – yeahhhhRIGHT

0

此語句之後,char [] mf1 = mostFamous.toCharArray();

mf1[0]=H, mf1[1]=e, mf1[1]=y... 
在這條線

所以,char current = mf1[dex]; 所以,在第一次迭代中,current=H,第二次迭代current=e...

+0

感謝您的明確解釋:) – yeahhhhRIGHT

0
char current = mf1[dex]; 

這條線從mf1 char數組獲取值並根據dex分配給current變量,dex可以作爲索引到ARR ay元素,它隨着運行循環而增加。

+0

yup。謝謝bhai :)我現在明白了 – yeahhhhRIGHT

0

char current = mf1[dex]; 

被置於內部的for循環,其中所述可變地塞米松在每次循環迭代時間遞增。變量dex是數組的從零開始的索引。在賦值運算符(=)的左側,聲明瞭一個名稱爲的變量,其類型爲char。賦值運算符的右側,你可以訪問您CharArray的DEX個字符,如果你從零開始計數。賦值運算符將您聲明的變量與您在右側指定的字符的值綁定。

例如,循環第一次運行時,dex將從0開始,因此mf1[dex](或mf1[0])僅爲'H'。

+0

非常感謝你的回答。我明白了。 :) – yeahhhhRIGHT

0

這裏是溶液

class SpaceRemover{ 

    public static void main(String[] args){ 

     String mostFamous = "Hey there stackoverFLow  "; 

      char [] mf1 = mostFamous.toCharArray(); 

      // mf1 contains={'H', 'e','y',' ','t','h',.........} 

      for(char current: mf1) 

      { 

     //the for-each loop assigns the value of mf1 variable to the current variable 

       //At first time the 'H' is assigned to the current and so-on 

       System.out.print(current==' '?'.':current); 

      } 

      System.out.println(); 



      } 

     } 
    } 
0

它的索引dexchar可變current在分配char陣列mf1的元件。

請注意,可以使用foreach語法簡化for循環和該行;這兩個碼塊是等效的:

// Your code 
for(int dex = 0; dex<mf1.length;dex++) { 
    char current = mf1[dex]; 

// Equivalent code 
for (char current : mf1) { 

但進一步,整個方法可以由一個行代替:

public static void main(String[] args){ 
    System.out.println("Hey there stackoverFLow  ".replace(" ", ".")); 
} 
0
char current = mf1[dex]; 

這將在字符數組索引爲DEX返回焦炭元件

這是數組的一個基本用法。

祝你好運與你的研究。

+0

謝謝先生。 是的,我會盡我所能。 :) – yeahhhhRIGHT