Java for loop isn't terminating in my code -
for reason loop not terminating in capitalizefirstsentence method. set breakpoint @ line , condition (i != -1) unmet, loop should terminate, doesn't!
it works when use (i > 0) condition.
i'm not sure what's going on here.
import javax.swing.joptionpane; public class sentencecapitalizer { //main method public static void main(string[] args) { string input; //creates string hold keyboard input //prompt user enter string using joptionpane , set equal input input = joptionpane.showinputdialog("enter string. "); //display new string first letter of each sentenced capitalized joptionpane.showmessagedialog(null, capitalizefirstsentence(input)); //exit program system.exit(0); } //capitalize first letter of each sentence public static string capitalizefirstsentence(string in) { //creates stringbuilder object initiralized string argument "in" stringbuilder temp = new stringbuilder(in); //capitalize first letter of string if string length > 0 if (temp.length() > 0) { temp.setcharat(0, character.touppercase(temp.charat(0))); } //sets equal index of space, //keep capitalizing first letters of each sentence (loops each time capitlizes letter) //until end of string (int = temp.indexof(". ")+1; != -1; i++) { //checks spaces , moves index first character of next sentence while (i < temp.length() && temp.charat(i) == ' ') { i++; } //capitalize character temp.setcharat(i, character.touppercase(temp.charat(i))); //index end of sentence = temp.indexof(". ", i); } //convert temp string , return our new first-sentenced-capitalized string return temp.tostring(); } }
first, not idea modify loop-controlling variable inside loop - quite hard read , understand such code, , prone errors.
now, example:
for (int = temp.indexof(". ")+1; != -1; i++)
this means:
- initialize
i
temp.indexof(". ")+1
, >= 0 - terminate if
i == -1
- after each iteration, increment
i
1
so:
- at start, cycle won't terminate because initialization returns >= 0
- each iteration, loop body set
i = temp.indexof(". ", i);
, >= -1 - after each iteration,
i
incremented 1, >= 0 - as
i
>= 0, never meet conditioni == -1
, never terminate
Comments
Post a Comment