【问题标题】:Java for loop isn't terminating in my codeJava for 循环没有在我的代码中终止
【发布时间】:2016-04-27 09:28:49
【问题描述】:

由于某种原因,我的 for 循环没有在我的 CapitalizeFirstSentence 方法中终止。我在该行设置了一个断点并且条件(i!= -1)未满足,因此循环应该终止,但它没有!

当我使用 (i > 0) 作为条件时,它可以工作。

我不确定这里发生了什么。

import javax.swing.JOptionPane;

public class SentenceCapitalizer {


    //Main Method
    public static void main(String[] args) {
        String input; //creates a String to hold keyboard input

        //Prompt the user to enter a String using JOptionPane and set it equal to input
        input = JOptionPane.showInputDialog("Enter a string. ");

        //Display the new String with the first letter of each sentenced capitalized
        JOptionPane.showMessageDialog(null, CapitalizeFirstSentence(input));

        //Exit the program
        System.exit(0);
    }


    //Capitalize first letter of each sentence
    public static String CapitalizeFirstSentence(String in)
    {
        //Creates a StringBuilder object initiralized to the String argument "in"
        StringBuilder temp = new StringBuilder(in);

        //Capitalize first letter of the string if string length is > 0
        if (temp.length() > 0)
        {
            temp.setCharAt(0, Character.toUpperCase(temp.charAt(0)));
        }

        //sets i equal to index of the space, 
        //keep capitalizing first letters of each sentence (loops each time it capitlizes a letter)
        //until very end of the String
        for (int i = temp.indexOf(". ")+1; i != -1; i++)
        {
            //Checks for extra spaces and moves index to first character of next sentence
            while (i < temp.length() && temp.charAt(i) == ' ')
            {
                i++;
            }

            //Capitalize character
            temp.setCharAt(i, Character.toUpperCase(temp.charAt(i)));

            //Index the end of the sentence
            i = temp.indexOf(". ", i);
        }

        //Convert temp to a String and return our new first-sentenced-capitalized String
        return temp.toString();

    }

}

【问题讨论】:

标签: java loops for-loop while-loop stringbuilder


【解决方案1】:

首先,在 for 循环中修改循环控制变量不是一个好主意——这样的代码很难阅读和理解,而且容易出错。

现在,以您为例:

for (int i = temp.indexOf(". ")+1; i != -1; i++)

这意味着:

  • i初始化为temp.indexOf(". ")+1,始终>= 0
  • 如果i == -1 则终止
  • 每次迭代后,将 i 递增 1

所以:

  • 在开始时,循环不会终止,因为初始化总是返回 >= 0
  • 每次迭代,循环体都会设置i = temp.indexOf(". ", i);,即>= -1
  • 每次迭代后,i 将递增 1,因此现在 >= 0
  • 由于i 总是>= 0,它永远不会满足条件i == -1,因此永远不会终止

【讨论】:

    【解决方案2】:

    这一行:for (int i = temp.indexOf(". ")+1; i != -1; i++) 将 i 初始化为 indexOf + 1 的结果。如果没有命中,IndexOf 给出 -1,但你总是在初始化时加 1,所以它永远不会小于 0。

    在那里使用i &gt; 0 似乎非常好。

    【讨论】:

    • 不是这么简单 - OP 正在他们的循环中修改 i
    • 是的,没错。你的答案更好。
    猜你喜欢
    • 2018-12-18
    • 2021-09-18
    • 1970-01-01
    • 2020-07-05
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多