【发布时间】:2017-02-24 23:13:37
【问题描述】:
我正在尝试编写一个程序,对于每个第 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 个单词只有空格。我觉得这是由于变量在循环内外没有相互交流。任何帮助,将不胜感激。谢谢。
【问题讨论】:
标签: java string loops variables