Hey everybody. I have a question on how to break out of a java loop. Here is a break down of what I am doing. I have 3 arrays "chrs" and "value" and "NumTimes"; "chrs" is an array of characters that has been read in from an input file. Value should be storing unique characters from chrs, and Numtimes will count if a letter has repeated itself. In the end I am looking to construct frequency information.

Example output:

chrs: The quick brown fox jumped over the lazy dog.
value: The quickbrownfxjmpdvlazyg.
NumTimes: 224812.......

(although, since the "t"s are compared in ASCII I am assuming that T and t will be different.)

Here is my code where I am having issues:

//Special Case. First Element
    		Value[0] = chrs[0];
    		NumTimes[0] = 1;
    		int ptr = 1;
    		System.out.print("\nFirst Values in...\n");
    		System.out.print("Testing ptr="+ptr+"\n--------\n");
    		
    		for(int i = 1; i < count;){
    			System.out.print("Testing i="+i+"\n");
    			for(int j = 0; j < ptr;){
    				System.out.print("Testing j="+j+"\n");
    				System.out.print("Testing ptr="+ptr+"\n");
    				//Case in which the 2 match
    				if(chrs[i]==Value[j]){
    					NumTimes[j]=NumTimes[j]+1;
    					i++;
    				}
    				//They don't match, but more 'j' to check
    				else if(chrs[i]!=Value[j] && j < ptr){
    					j++;  //check the next 'j'
    				}
    	//They don't match, no more 'j' to check; place into value
    				else if(chrs[i]!=Value[j] && j==ptr){
    					Value[ptr]=chrs[i];
    					NumTimes[ptr]=NumTimes[ptr]+1;
    					ptr = ptr+1;
    					i++;
    				}else{
    	//Poor Man's 'catch' statement   					          System.out.print("Houston, we've had a problem.");
    				}
    			}
    		}

My gut is telling me that my error (which puts me into an infinite loop) is in the first "else if" statement. I thought that by incrementing "j" it would break the current iteration of the loop and advance to the next J. I guess my question is: is there some form of "Next J" function call that will move to the next loop iteration?

Regards,
Dragonfyre


As an FYI "count" is the length of "chrs."

is there some form of "Next J" function call that will move to the next loop iteration?

Regards,
Dragonfyre


As an FYI "count" is the length of "chrs."

try using continue.

I think I see the logic, but I'm not 100% sure. I see no reason why you are not placing the i++ in your outer loop or why you would want it inside your inner loop. Your job, it seems to me, is to go through chrs[] a character at a time, then go through your inner loop to see if that character has occurred. If and when you find that it HAS occurred, you can break out of the loop by making j greater than ptr. You can also design your inner loop so that it uses a boolean flag. Either is acceptable. I personally prefer the boolean flag since I think it improve readabilty. Regardless, I think it is a mistake to put code like i++ or j++ inside the inner loop's body. I would design it like this, using descriptive variable names:

for (int i = 0; i < chrs.length; i++)
{
   // extract ith character
   boolean charHasOccurred = false;
   for (int j = 0; j < Value.length && !charHasOccurred; j++)
   {
      // check whether char has occurred.  If so, flag charHasOccurred as true and increment number of times char has occurred in NumTimes[]
   }

   if (!charHasOccurred)
   {
      // add ith character to Value[] array and set NumTimes[] element to 1 for that element
   }
}

Oh boy... Lots of problems...
1) If you want to increment i (or j) outside the for loop, use a while statement!!
2) Your inner loop has an "if-elseif-elseif-else" structure... There are four possible code paths. Only one of those code paths increment j.
3) Java convention is to have variable instances start with a lowercase letter... so it would be numTimes, not NumTimes.
4) This is terribly inefficient and cumbersome using just arrays. You should be using String, ArrayList, StringBuilder, etc.
5) Do you want to learn to program or is this for a school assignment? The advice that improved the quality of my code more than anything else was to stop using comments and instead write a method everywhere I feel a comment is necessary... Below is the code, working, using this strategy. Keep in mind that I could write this code in 1/10th the size, but it would be very difficult to read and understand...
6) There is a 'break' keyword that you can use to break out of the inner loop.

public void doExample()
    {
        char[] chrs="The quick brown fox jumped over the lazy dog.".toCharArray();
        int[] numTimes=new int[chrs.length];
        char[] value=new char[chrs.length];
        int ptr=0;
        for (int i=0;i<chrs.length;i++)
        {
            if (!containsCharacter(value, chrs[i], ptr))
            {
                ptr=addUniqueCharacter(value, numTimes, chrs[i], ptr);
            }
            else
            {
                incrementUniqueCharacterCount(value, numTimes, chrs[i], ptr);
            }
        }

        System.out.println("chrs="+(new String(chrs, 0, chrs.length)));
        System.out.println("value="+(new String(value, 0, ptr)));
        for (int i=0;i<ptr;i++)
        {
            System.out.print(numTimes[i]);
        }
        System.out.println();
    }

    private boolean containsCharacter(char[] uniqueCharacters, char testChar, int nUniqueCharacters)
    {
        return getCharacterIndex(uniqueCharacters, testChar, nUniqueCharacters)!=-1;
    }


    private int addUniqueCharacter(char[] uniqueCharacters, int[] nOccurrences, char charToAdd, int nUniqueCharacters)
    {
        uniqueCharacters[nUniqueCharacters]=charToAdd;
        nOccurrences[nUniqueCharacters]=1;
        return nUniqueCharacters+1;
    }

    private int getCharacterIndex(char[] uniqueCharacters, char testChar, int nUniqueCharacters)
    {
        for (int i=0;i<nUniqueCharacters;i++)
        {
            if (uniqueCharacters[i]==testChar)
            {
                return i;
            }
        }
        return -1;
    }

    private void incrementUniqueCharacterCount(char[] uniqueCharacters, int[] nOccurrences, char charToIncrement, int nUniqueCharacters)
    {
        int idx=getCharacterIndex(uniqueCharacters, charToIncrement, nUniqueCharacters);
        if (idx==-1)
        {
            throw new IllegalArgumentException("Argument 'charToIncrement' not in array 'uniqueCharacters'");
        }
        nOccurrences[idx]=nOccurrences[idx]+1;
    }
commented: Nice first post :) And: Using code tags correctly :) +17
commented: Ditto tux4life. Some good guidance and thanks for using code tags. +19

Wow. Thanks to everyone for responding.

1.) First thing I would like to say is that yes, this is something that I am doing to teach myself Java. I have for a while been trying to teach myself.

2.) Between the time I posted the initial question and now, I have been playing with FLAG a little, so I am glad to see it was mentioned. I of course didn't use it quite as well.

3.) ZipXap: thanks for the suggestions on improving efficiency. I will start reading and learning about other ways.

4.) Good to know on the 'break' keyword. Thanks.

5.) I will work more on naming conventions! Thanks everyone!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.