0

I have no idea why my second for loop won't execute.. It compiles but when I run this it does not work ~_~

import java.util.Scanner;

public class ranges
{


 public static void main (String[] args)

  {

 Scanner scan = new Scanner (System.in);

       int size;
       int input;
       int count = 0;
       int occurence = 0;
       System.out.print ("Please enter the size of your array: ");
       size = scan.nextInt();
       int[] list = new int[size];



       for (int index = 0 ; index < list.length ; index++)
       {
           System.out.print ("Please enter an integer between 0 to 50: ");
           input = scan.nextInt();

           if ( input >= 0 && input <= 50 )
           {
               list[index] = input;
            }
           else
           {
               System.out.println ("Invalid output, please try again");
               index--;
           }
        }




       int right = (list.length)-1;
       int left = 0;

        for (int counter = left ; counter < list.length ; counter++)
        {
            while ( right >= left )
            {
                if ( list[left] == list[right] )
                {
                    occurence++;
                    right--;
                }
            }
           right = (list.length)-1;
           System.out.println ("The number " + list[left] + " was added " + occurence + "4 times");
        }

         for (int value : list)
        {
            System.out.print (value + " ");
        }
       ;








    }
}

My updated for loop to evaulate occurences

for (int left = 0 ; left < list.length ; left++)

{

        while ( right >= left )
        {
            if ( list[left] == list[right] )
            {
                occurence++;

            }
            right--;
        }


       System.out.println ("The number " + list[left] + " was added " + occurence + " times");
       right = (list.length)-1;
       occurence = 0;
    }

I have cleaned it up a bit, and now occurences are same as the inputs

6
  • 1
    "It compiles but when I run this it does not work ~_~" - well what happens? do you get an exception? Commented Oct 25, 2012 at 21:37
  • @Mihai Stancu: The homework tag was declared obsolete! Commented Oct 25, 2012 at 21:37
  • 1
    @MihaiStancu no, homework tag must not be used. Commented Oct 25, 2012 at 21:37
  • Good comments above, and answers below. One additional comment: It's almost always a bad idea to modify the loop variable inside the loop. It may work, but don't get into the habit of doing it. Find another way to structure you code so that you don't have to do that. If I were the instructor, I'd fail you for that, regardless of whether the program worked. Commented Oct 25, 2012 at 21:39
  • This is not homework guys >_< Commented Oct 25, 2012 at 21:53

3 Answers 3

1

You second for is also working. The problem is in while loop condition i.e. while ( right >= left ). If list[left] == list[right] is not equal, it goes in infinite loop as neigther right nor left changing in that case.

I think, you need to change your while as below(move right-- outside the if condition):

  while ( right >= left )
   {
     if ( list[left] == list[right] )
      {
        occurence++;
      }
      right--;
    }

Two more issues:

Please re-initialize occurence =0; before the while loop so that it counts occurence of each number and remove 4 from your System.out.println() e.g. below:

for (int counter = left ; counter < list.length ; counter++)
{ 
  occurence = 0; //< initialize to 0
  while ( right >= left )
  {
      if ( list[left] == list[right] )
      {
         occurence++;
       }
           right--;
   }
   right = (list.length)-1;
       //remove 4 after "occurance +"
   System.out.println ("The number " + list[left] + 
                                            " was added " + occurence + " times");
 }

EDIT: working sample with HashMap:

       Map<Integer, Integer> scannedNums = new HashMap<Integer, Integer>();
        for (int counter = left ; counter < list.length ; counter++)
        {
            if(scannedNums.get(list[counter]) == null){
                scannedNums.put(list[counter], 1);
            }else{
                int currentCount = scannedNums.get(list[counter]);
                scannedNums.put(list[counter], currentCount+1);
            }
        }

        Set<Integer> nums = scannedNums.keySet();
        Iterator<Integer> numIter = nums.iterator();
        while(numIter.hasNext()){
            int number = numIter.next();
            System.out.println ("The number " + number + 
                    " was added " + scannedNums.get(number) + " times");
        }
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks, sorry about that. But it does not give correct number of occurences in the array, is there something wrong in my formula>?
@Aaron: There are two more issues. Please look at the updated answer.
Occurence variable is already initialized to 0 and I have removed the 4
@Aaron: You need to reinitilize within for loop otherwise it will keep counting number one occurence with number 2 and so on which you won't want. Through occurance you are trying to count occurance of each number, right?
Ok thank you, it's sort of working but it will check again for the same number, for example, if i enter size 5 array with 1,1,1,2,3 the first output is correct but second one will say 1 has been entered twice and third output will say 1 has been entered once.
|
0

Just a quick look, and suggestion for the future.

This code:

  while ( right >= left )
    {
        if ( list[left] == list[right] )
        {
            occurence++;
            right--;
        }
    }

suggests that if list[left] != list[right], yet right is still >= left, this loop will never stop. You might want to move the right-- OUTSIDE of the if statement, if all you want is a count of how many occurrences are found.

Finally, when you say "the loop doesn't work", that's a little less than helpful. Perhaps showing your output, or the WAY in which it doesn't work would be better.

4 Comments

Thanks, now it's working properly but looks like the formula is wrong. I'm trying to get how many occurences of the same number the user has entered in the array. Do i have the correct formula?
SHOW YOUR TEST. It's SO much easier to debug someone else's code when they actually bother to tell you what it's really doing.
If I entered 10,30,10,20,30... I'd expect it to say "2 of 10, 2 of 30, 1 of 10, 1 of 20, and 1 of 30"... according to what you have. Maybe you should look up the idea of a Map to store the values and how many times they were typed in.
Our class has not covered that concept yet. This is just one question out of the textbook for practice. Sorry.
0

What error does it give?

One immediate problem I see is that if there are no occurrences, the while loop will run for ever. Also the first for loop could give index out of bounds.

For the first loop, instead of:

    for (int index = 0 ; index < list.length ; index++)
   {
       System.out.print ("Please enter an integer between 0 to 50: ");
       input = scan.nextInt();

       if ( input >= 0 && input <= 50 )
       {
           list[index] = input;
        }
       else
       {
           System.out.println ("Invalid output, please try again");
           index--;
       }
    }

I would do:

    for (int index = 0 ; index < list.length ; ++index)
    {
         while(true)
         {
             System.out.print ("Please enter an integer between 0 to 50: ");
             input = scan.nextInt();
             if ( input >= 0 && input <= 50 )
             {
                list[index] = input;
                break;
             }
             System.out.println ("Invalid output, please try again");
         }
     }

And for the second loop:

    for (int counter = left ; counter < list.length ; counter++)
    {
        occurence = 0;
        for( int i = counter; i <= right; ++i)
        {
            if( list[left] == list[i] )
                 ++occurence;
        }
       System.out.println ("The number " + list[left] + " was added " + occurence + " times");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.