• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Please check my code

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i'm starting to complete java exercises i find online (starting from the basics).

the task is: Exercise SumAndAverage (Loop): Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output shall look like:

but in my program, when i enter an upperlimit of say 10 which totals to 55. i expect the average to be 5.5. but my program returns 5.0.

can you please tell me how to fix this?

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Emanuel Mensa wrote:but in my program, when i enter an upperlimit of say 10 which totals to 55. i expect the average to be 5.5. but my program returns 5.0.


That's because number is an int, which can only hold integer values (not fractional values such as 5.5).

Lines 34 and 35 are wrong. Don't store the result in number. Remove those lines, just return number divided by upperBound there. Since upperBound is a double, the result will be a double and the calculation will be correct.

You're also doing things wrong with static. When a variable is static, it means that only one copy of it exists which is shared by all instances of a class (see Understanding Instance and Class Members).

You're first setting upperBound in line 46, then you're passing it to the constructor of SumAndAverage in line 47, where you're setting it again (line 17), as if it is an instance variable instead of a class variable. Then you're again passing it to the calc method (line 49). The calc method doesn't need to get upperBound as a parameter - it can access the member variable (line 5) directly.
 
reply
    Bookmark Topic Watch Topic
  • New Topic