Java for 循环在我的代码中没有终止
2022-09-03 04:58:20
由于某种原因,我的 for 循环在我的 CapitalizeFirstSentence 方法中没有终止。我在该行设置了一个断点,条件(i != -1)未满足,因此循环应该终止,但它不会终止!
当我使用(我>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();
}
}