Results 1 to 13 of 13
  1. #1
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default trouble with showing the average with functions and loops

    Hello, i won't lie this is a homework. We had to write a program that would read the names of cities and then their population. For this part it works great, the sentinal works too. Its just the function that is supposed to find the average of the population. When i try to divide (in the average function) it show the last population number????

    Like this:


    Enter the name of a city? sdfds dsfds .
    Enter the population: 2342 23432


    City Population
    ----- ----------
    sdfds 2342
    dsfds 23432
    The AVERAGE is 23432.0



    What is weird is that if i try to show the sum, it show the sum of all the populations. It just doesn't let me divide it by anything. Based on this code, any idea on how to solve this?? Any tips would be appreciated.



    Java Code:
    import java.lang.*;
    import java.util.Scanner;
    
    
    
    public class test128 {
    
    
    static int counter;
    static Scanner keyboard = new Scanner(System.in);
    static float average2;
    static int sum;
    static int pop;
    static int x;
    
    
    
    
        static int readarray(String word, int[] population, String[] arraycity)
        {
       for (counter=0; word.compareTo(".")!=0; counter++)
            {
             arraycity[counter] = word;
             word=keyboard.next();
            }
    
    
    
    System.out.print("Enter the population: ");
          for (x=0; x< counter; x++)
            {
              pop=keyboard.nextInt();
    
              population[x] = pop;
            }
       return counter;
        }
    
    
    
    
    static float average(int counter, int[]population)
        {
       sum=0;
        int i;
              for (i=0; i<counter; i++)
            {
                sum=sum+pop;
            }
        average2=(sum/counter);
        return average2;
    }
    
    
    
    
    
    
    
        static void showarray(int counter, int [] population, String []arraycity)
        {
            System.out.println("City"+"    "+"Population");
            System.out.println("-----"+"    "+"----------");
            for (int x=0; x<counter;x++)
            {
                System.out.println(arraycity[x]
                         +
                        "     " + population[x]);
            }
        }
    
    
    
    
    
        public static void main(String[] args)
        {
            String [] arraycity;
            arraycity=new String[50];
    
            int [] population;
            population=new int[50];
    
           System.out.print("Enter the name of a city? ");
           String word=keyboard.next();
    
    
    
    
    
    
    
        readarray(word, population, arraycity);
        average(counter, population);
    
        System.out.print("\n\n");
    
        showarray(counter, population, arraycity);
     System.out.print("The AVERAGE is "+average2);
    
    
    
        }
    }
    Last edited by anonymous445; 01-29-2011 at 06:17 PM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    When i try to divide (in the average function) it show the last population number?

    So, how big is counter when the average() method is called? I ask because if counter were 1 the for loop would only look at the first value and the division would be by one, leading to the behaviour you describe.

    You can check with

    Java Code:
    static float average(int counter, int[]population)
    {
       System.out.println("At average(), counter=" + counter);
       sum=0;
        int i;
       for (i=0; i<counter; i++)
       {
          sum=sum+pop;
       }
       average2=(sum/counter);
       return average2;
    }

    If counter does not have the value you expect you need to go back to where you thought you gave it the correct value and figure out why that didn't happen.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Also what is pop in that average() method supposed to be? You add it together counter times and then return the result divided by counter. Ie the average() method will always return the value of pop.

    Perhaps you should be adding something else to sum each time around the for loop.

  4. #4
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    So, how big is counter when the average() method is called? I ask because if counter were 1 the for loop would only look at the first value and the division would be by one, leading to the behaviour you describe.

    You can check with

    Java Code:
    static float average(int counter, int[]population)
    {
       System.out.println("At average(), counter=" + counter);
       sum=0;
        int i;
       for (i=0; i<counter; i++)
       {
          sum=sum+pop;
       }
       average2=(sum/counter);
       return average2;
    }

    If counter does not have the value you expect you need to go back to where you thought you gave it the correct value and figure out why that didn't happen.
    thx for the code but i already tried that.(tried your code and did before a writeline with the counter at the end of the main and it returns the same thing). That is the problem with my code. i know the counter does have the right value. If you enter 2 cities for example, it says the counter = 2.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    i know the counter does have the right value.
    I agree. (I checked after I posted and realised that what I was suggesting would lead to the first population value being displayed not the last...)

    Hence my second post.

  6. #6
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    Also what is pop in that average() method supposed to be? You add it together counter times and then return the result divided by counter. Ie the average() method will always return the value of pop.

    Perhaps you should be adding something else to sum each time around the for loop.
    pop is supposed to variable in wich i put the population number. But i may be wrong but i don't think there is anything wrong with the sum because when i do this
    System.out.print("The sum is "+sum);
    it shows the proper sum. ex:


    run:
    Enter the name of a city? dsfds dsfds .
    Enter the population: 40 40


    City Population
    ----- ----------
    dsfds 40
    dsfds 40
    The sum is 80The sum is 80

  7. #7
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    yea, it should work like. If the sum is working and the counter has the right value, if you divide the sum by the counter, it should show the average. Weird.

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    You got "lucky" by entering 40 twice. Here's what I see:

    Java Code:
    Enter the name of a city? Asd Dsa .
    Enter the population: 40 50
    sum=100
    
    
    City    Population
    -----    ----------
    Asd     40
    Dsa     50
    The AVERAGE is 50.

    This is using the code

    Java Code:
    static float average(int counter, int[] population) {
        sum = 0;
        int i;
        for (i = 0; i < counter; i++) {
            sum = sum + pop;
        }
        System.out.println("sum=" + sum);
        average2 = (sum / counter);
        return average2;
    }

    The important thing is that pop never changes its value within the for loop. You keep adding the same value over and over again. In my case that value was 50 - ie the population of the last city to be entered.

  9. #9
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    You got "lucky" by entering 40 twice. Here's what I see:

    Java Code:
    Enter the name of a city? Asd Dsa .
    Enter the population: 40 50
    sum=100
    
    
    City    Population
    -----    ----------
    Asd     40
    Dsa     50
    The AVERAGE is 50.

    This is using the code

    Java Code:
    static float average(int counter, int[] population) {
        sum = 0;
        int i;
        for (i = 0; i < counter; i++) {
            sum = sum + pop;
        }
        System.out.println("sum=" + sum);
        average2 = (sum / counter);
        return average2;
    }

    The important thing is that pop never changes its value within the for loop. You keep adding the same value over and over again. In my case that value was 50 - ie the population of the last city to be entered.
    hmm that might be the problem. But i can't figure out another way to find the sum. Like is there a way of figuring out the sum of the numbers in my table population.

  10. #10
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by anonymous445 View Post
    hmm that might be the problem. But i can't figure out another way to find the sum. Like is there a way of figuring out the sum of the numbers in my table population.
    ive sent the array population to the function average. I also sent the counter. Like i don't think java will let me divide the array population by the counter.

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    ive sent the array population to the function average. I also sent the counter.
    Yes. And it would be most straightforward if you used these values and not the static class ones to determine the average. (Actually the counter you use is the one you pass - it just happens to have the same value as the static class counter. Don't worry too much about this.)

    i don't think java will let me divide the array population by the counter

    Java doesn't let you directly do arithmetic with arrays (sum or average them). But you can use a for loop to work on them one element at a time.

    The use of pop is wrong in the for loop. It is (and stays being) the value of the last city to be entered. There is no reason to keep adding this to the sum. Basically you need to think of something to replace it. Something (as you're begining to think about) to do with that population array.

    Java Code:
    static float average(int counter, int[] population) {
        sum = 0;
        int i;
        for (i = 0; i < counter; i++) {
            sum = sum + ...; // population[???]
        }
        average2 = (sum / counter);
        return average2;
    }

  12. #12
    anonymous445 is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    Yes. And it would be most straightforward if you used these values and not the static class ones to determine the average. (Actually the counter you use is the one you pass - it just happens to have the same value as the static class counter. Don't worry too much about this.)




    Java doesn't let you directly do arithmetic with arrays (sum or average them). But you can use a for loop to work on them one element at a time.

    The use of pop is wrong in the for loop. It is (and stays being) the value of the last city to be entered. There is no reason to keep adding this to the sum. Basically you need to think of something to replace it. Something (as you're begining to think about) to do with that population array.

    Java Code:
    static float average(int counter, int[] population) {
        sum = 0;
        int i;
        for (i = 0; i < counter; i++) {
            sum = sum + ...; // population[???]
        }
        average2 = (sum / counter);
        return average2;
    }
    I think i got it thanks :)


    Enter the name of a city? dsfdsf sdfds .
    Enter the population: 67000 45000


    City Population
    ----- ----------
    dsfdsf 67000
    sdfds 45000
    The average is 56000.0

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    I think i got it thanks

    You're welcome. One thing you could think about is removing those static variables. pop got you into trouble and that could be taken as a sign that something's wrong. In general terms it is better to pass values (like the population array) rather than rely on static values (like pop). Likewise since readarray() returns the number of entries read, is there any need for the static counter variable (rather than just having it as a local variable of the main() method and passing it as a value when other methods need it)?

    Something to think about...

    -----------------------------

    But, in any case, you should use standard Java naming conventions. It's a small point (little more than a habit), but an important one. Class names start with a capital letter and camelCase is used when a name consists of multiple lexical elements: so, Test128 and readArray() etc.

Similar Threads

  1. Need help to find average
    By kevinsoto in forum New To Java
    Replies: 4
    Last Post: 11-04-2010, 01:54 PM
  2. trouble with loops
    By relics in forum New To Java
    Replies: 1
    Last Post: 09-22-2010, 11:01 PM
  3. average
    By anjigadu in forum New To Java
    Replies: 4
    Last Post: 09-19-2010, 09:52 PM
  4. Need help getting average
    By soccer_kid_6 in forum New To Java
    Replies: 15
    Last Post: 09-12-2010, 11:59 PM
  5. Replies: 2
    Last Post: 02-23-2009, 02:18 AM

Posting Permissions

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