【问题标题】:String not concatenating with char that gets updated with each loop字符串不与每个循环更新的 char 连接
【发布时间】: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


    【解决方案1】:
    for (int i2 = newWord.length(); i2==-1; i2--){
    

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

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

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

    【讨论】:

    • 非常感谢你的完美!!
    【解决方案2】:

    我同意 for 循环正在做什么的陈述,但您也可能想要更改 a 的初始值,或者在循环中从后减量更改为前减量。 .

    要么

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

    或者

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

    否则会出现索引越界错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2016-12-15
      • 2012-05-18
      • 2017-12-18
      • 1970-01-01
      • 2019-04-15
      相关资源
      最近更新 更多