Java for循环不会在我的代码中终止

Tom*_*hao 16 java stringbuilder loops for-loop while-loop

由于某种原因,我的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();

    }

}
Run Code Online (Sandbox Code Playgroud)

Jir*_*sek 24

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

现在,举个例子:

for (int i = temp.indexOf(". ")+1; i != -1; i++)
Run Code Online (Sandbox Code Playgroud)

这意味着:

  • 初始化itemp.indexOf(". ")+1,始终> = 0
  • 终止if i == -1
  • 每次迭代后,递增i1

所以:

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


sfT*_*mas 7

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

i > 0在那里使用似乎非常好.

  • 这不是这么简单 - OP正在修改循环中的`i`. (2认同)