Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop isn't terminating in my code

For some reason my for loop is not terminating in my CapitalizeFirstSentence method. I set a breakpoint at that line and the condition (i != -1) is unmet, so the loop should terminate, but it doesn't!

It works when I use (i > 0) for the 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 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();

    }

}
like image 698
Tommy Saechao Avatar asked Jan 21 '16 08:01

Tommy Saechao


People also ask

Why does my for loop not stop Java?

It will not stop because you use "or" || in your while statement. so If one expression at least is true then the loop will keep executing. You have to use "and" && instead.

Why is my while loop not stopping?

The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.

How do you abort a for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

How do you stop a running loop in Java?

The break statement is used to terminate the loop immediately. The continue statement is used to skip the current iteration of the loop. break keyword is used to indicate break statements in java programming. continue keyword is used to indicate continue statement in java programming.


2 Answers

First, it is not a good idea to modify the loop-controlling variable inside a for loop - it is quite hard to read and understand such code, and is prone to errors.

Now, to your example:

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

This means:

  • Initialize i to temp.indexOf(". ")+1, which is always >= 0
  • Terminate if i == -1
  • After each iteration, increment i by 1

So:

  • At the start, the cycle won't terminate because the initialization always returns >= 0
  • Each iteration, the loop body will set i = temp.indexOf(". ", i);, which is >= -1
  • After each iteration, i will be incremented by 1, so it will now be >= 0
  • As i is always >= 0, it will never meet the condition i == -1 and thus will never terminate
like image 132
Jiri Tousek Avatar answered Oct 19 '22 18:10

Jiri Tousek


This line: for (int i = temp.indexOf(". ")+1; i != -1; i++) initializes i to be the result of indexOf + 1. IndexOf gives -1 if there is no hit, but you always add 1 to that during initialization, so it'll never be smaller than 0.

Using i > 0 seems perfectly fine there.

like image 27
sfThomas Avatar answered Oct 19 '22 18:10

sfThomas