2017-02-24 53 views
-1

我正在試圖製作一個程序,爲每個第n個字,該字符串中的單詞被顛倒。然而,我已經對循環中的變量發生了很多混淆,因爲不是顛倒這個單詞,而是讓整個事物變成空白。這是我的代碼,它只是主程序反轉過程的返回方法;字符串與每個循環得到更新的字符不連接

public static String reverse(String s, int n) { 

    String[] parts = s.split(" "); //separating each word of the string into parts of an array 
    String finalS = ""; //this will be the new string that is printed with all the words reversed\ 
    char a; 

    for (int i = 0; i < parts.length; i++) { 

     int wordCount = i + 1; //making it so that it's never 0 so it can't enter the if gate if just any number is entered 

     if (wordCount%n==0) { //it's divisible by n, therefore, we can reverse 
      String newWord = parts[i]; //this word we've come across is the word we're dealing with, let's make a new string variable for it 
      for (int i2 = newWord.length(); i2==-1; i2--){ 
       a = newWord.charAt(i2); 
       finalS += a; 
      } 
     } 
     else { 
      finalS += parts[i]; //if it's a normal word, just gets added to the string 
     } 

     if (i!=parts.length) { 
      finalS += " "; 
     } //if it's not the last part of the string, it adds a space after the word 
    } 

    return finalS; 
} 

比第n個其他的每一個字返回完美的,沒有變化,但第n詞只是有空格。我覺得這是由於變量之間沒有互相交流和循環。任何幫助,將不勝感激。謝謝。

回答

0
for (int i2 = newWord.length(); i2==-1; i2--){ 

此循環將永遠不會做任何事情。它看起來像你可能想

for (int i2 = newWord.length() - 1; i2 >= 0; i2--){ 

一個for循環的第二個組成部分是,必須是真實的去循環,而不是結束循環的條件的條件。

+0

非常感謝您的完美! – petegoast

0

我同意關於for循環正在做什麼的聲明,但是您也想要更改a的初始值,或者在循環中更改從後減量變爲預減量。 ..

要麼

for (int i2 = newWord.length() - 1; i2 >= 0; i2--) 

或者

for (int i2 = newWord.length(); i2 >= 0; --i2) 

否則,你會得到一個指數超越界限的錯誤