Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By jim829

Thread: For Loop Problem

  1. #1
    CruelSoulz is offline Member
    Join Date
    May 2013
    Rep Power

    Question For Loop Problem

    Java Code:
    public static double calculateAverage(int[] myArray){
    double total = 0;
    int count  = 0;
    for(int i=0; i<myArray.length; i++){
    /* If the index of array is a negative value, ignore it*/
    while(myArray[i] >= 0){
    total += myArray[i];
    return total/count;
    When the for loop start looping, the compiler just stopped and doesn't crash or display any error messages. It still allows me to enter word/number into it even don't have any scanner. What's the problem ?
    Jcreator user here.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: For Loop Problem

    I believe you have some logic problems. If any of the elements in myArray are >= 0 then you will never return from the method. For example, say myArray[0] == 10. When i==0 you will never exit the while loop. From the comment and the name of the method I am guessing that you only want to average the positive values of the array.

    So you need only one loop and one if statement. Try again and I or someone else will help.

    CruelSoulz likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    CruelSoulz is offline Member
    Join Date
    May 2013
    Rep Power

    Default Re: For Loop Problem

    Owh .... I didn't realize that logic problem haha .... thanks

Similar Threads

  1. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  2. Problem with while loop
    By sassy1 in forum New To Java
    Replies: 12
    Last Post: 03-24-2011, 11:01 AM
  3. Problem with For Loop
    By dave12har in forum New To Java
    Replies: 5
    Last Post: 11-30-2010, 03:35 PM
  4. simple line problem / for loop problem
    By helpisontheway in forum New To Java
    Replies: 1
    Last Post: 11-17-2009, 06:12 AM
  5. Problem to use different for loop to add up
    By matt_well in forum New To Java
    Replies: 6
    Last Post: 08-03-2008, 10:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts