不与每个循环更新的char连接的字符串

时间:2017-02-24 23:13:38

标签: java string loops variables

我正在尝试制作一个程序,对于每个第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个单词只有空格。我觉得这是因为变量没有在循环中相互交流。任何帮助,将不胜感激。感谢。

2 个答案:

答案 0 :(得分:0)

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

这个循环永远不会做任何事情。看起来你可能想要

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

for循环的第二个组成部分必须为进入循环的条件,而不是结束循环的条件。

答案 1 :(得分:0)

我同意关于for循环正在做什么的陈述,但你也想要改变a的初始值,或者从你的循环中的后减量变为预减量...

无论

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

或者

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

否则您将获得索引超越边界错误