2017-03-08 63 views
-2

我知道編碼和練習問題,所以我可以變得更好。我在CodingBat上做了一個問題,但是我陷入了一個問題,我不明白爲什麼我的代碼不工作。增加計數器一次和兩次之間有什麼區別

問題是:給定一個字符串,返回一個字符串,其中原始字符中的每個字符都有兩個字符。

doubleChar("The") → "TThhee" 
doubleChar("AAbb") → "AAAAbbbb" 
doubleChar("Hi-There") → "HHii--TThheerree" 

我寫的代碼是

public String doubleChar(String str) { 
char[] STR = str.toCharArray(); 
     char[] two = new char[STR.length*2]; 
     int counter=0; 
     for(int i=0;i<STR.length;i++){ 
      two[counter]=STR[i]; 
      two[counter+1]=STR[i]; 
      counter++; 
     } 
     String b= new String(two); 
     return b; 
} 

output results //即時猜測反着的增量counter+1但只雖然counter++。我能得到更好的解釋嗎?

經過一段時間的搞亂之後,我找到了它,但我仍然不明白爲什麼原件沒有。我也是新來的編碼,所以我非常感謝幫助!

工作:

public String doubleChar(String str) { 
char[] STR = str.toCharArray(); 
     char[] two = new char[STR.length*2]; 
     int counter=0; 
     for(int i=0;i<STR.length;i++){ 
      two[counter]+=STR[i]; 
      counter++; 
      two[counter]=STR[i]; 
      counter++; 

     } 
     String b= new String(two); 
     return b; 
} 
+2

在每次迭代中,你寫兩個大字,但你只增加你的櫃檯一次。所以第一次迭代寫入字符0和1,第二次迭代寫入1和2,第三次寫入2和3等,而不是0,1,2和3,4和5 –

回答

0

功能,

counter++ 

相同

​​

在你的原代碼,您使用的值計數器計數+ 1,但你不要更改計數器中的值。您只需在單個計數器++操作中更改它,但必須有2個。或者,您可以編寫以下內容:

 two[counter]=STR[i]; //does NOT change the value of counter 
     two[counter+1]=STR[i]; //does NOT change the value of counter 
     counter += 2; //DOES change the value of counter 
+0

這是不正確的。這是因爲他在串聯。 – Mdjon26

+2

@ Mdjon26你錯了。這個答案是正確的。 –

+1

他在問他的原代碼有什麼問題,我看不到連接? – toongeorges

1

在您的原始解決方案中,您只會將計數器變量增加一次。

「counter + 1」不增加您的計數器值,它只是一個變量和一個數字的加法(counter + = 1可以遞增計數器變量的值)。

所以,當你寫:

two[counter]=STR[i]; 
    two[counter+1]=STR[i]; 
    counter++; 

這意味着(當計數器= 0)

two[0]=STR[i]; 
    two[0+1]=STR[i]; 
    0++; //So the value of the counter variable is still 0 here 

而在你的妥善解決

two[counter]+=STR[i]; 
    counter++; 
    two[counter]=STR[i]; 
    counter++; 

你增加你的計數器變量兩次,如此:

two[0]+=STR[i]; 
    0++; 
    two[1]=STR[i]; 
    1++; 
0

在原始:

counter++; 

應該是:

counter+=2; 
0

您需要通過2在你原來的代碼將增加counter並能正常工作。畫在紙上的輸出:

for(int i=0;i<STR.length;i++){ 
    two[counter]=STR[i]; 
    two[counter+1]=STR[i]; 
    counter++; 
} 

對於STR = "The"

i = 0: 
    counter = 0; 
    two[counter] = two[0] = "T"; 
    two[counter+1] = two[1] = "T"; 

i = 1: 
    counter = 1; 
    two[counter] = two[1] = "h"; (You just overwrote two[1] here, it was "T" but is now "h"); 
    two[counter+1] = two[2] = "h"; 

等。

現在與修正代碼:

for(int i=0;i<STR.length;i++){ 
    two[counter]=STR[i]; 
    two[counter+1]=STR[i]; 
    counter+=2; 
} 

i = 0: 
    counter = 0; 
    two[counter] = two[0] = "T"; 
    two[counter+1] = two[1] = "T"; 

i = 1: 
    counter = 2; 
    two[counter] = two[2] = "h"; 
    two[counter+1] = two[3] = "h"; 
相關問題