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番目の単語は空白があります。私はこれがループ内外で互いに話していない変数によるものだと感じています。どんな助けもありがとう。ありがとう。
本当にありがとうございました! – petegoast