The Artima Developer Community
Sponsored Link

Java Answers Forum
New to Java: How Do You Average Numbers?

1 reply on 1 page. Most recent reply: Sep 3, 2002 12:37 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Brook

Posts: 12
Nickname: brook
Registered: Sep, 2002

New to Java: How Do You Average Numbers? Posted: Sep 3, 2002 9:22 AM
Reply to this message Reply
Advertisement
I want to average three numbers, all hard coded. Then print them on the screen.

Example:

public class AverageNumbers
{
public static void main(String{}args)
{
int firstNo = 80
int secondNo = 85
int thirdNo = 90

print.out.println("80 and 85 and 90: " + (80 + 85 + 90)/3));
}
}

OK, it is full of errors, that's why I have posted it here to see what the correct
code would be. THANK YOU.


Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: New to Java: How Do You Average Numbers? Posted: Sep 3, 2002 12:37 PM
Reply to this message Reply
Here's one that works a little better:
public class AverageNumbers
{
   public static void main(String [] args)
   {
      int firstNo = 80;
      int secondNo = 85;
      int thirdNo = 90;
      
      System.out.println( "80 and 85 and 90: " + (80 + 85 + 90)/3 );
   }
}

The major differences are:
- Uses square braces to indicate args is an array.
- Semicolons after each statement (int declarations).
- Changed "print.out" to "System.out".
- Removed extra right-paren in the print statement.
- Most importantly, used the [ java ] tags to get nice formatting in the forum message.

It still has problems. Averaging ints is a dicey proposition, especially if there is a small number of them or if they have very large values. Values are hard-coded, particularly in the print statement. Probably, you would want to have a method that takes an array of ints and returns their average in a float, or maybe an int, if you don't care about the truncation (for instance, when positioning windows on a screen, you might do something like that, since you don't care wether it is off by a pixel).

Flat View: This topic has 1 reply on 1 page
Topic: HELP String Tokenizer and Calculations Previous Topic   Next Topic Topic: Simple Java code for me

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use