7
readers helped!

This helped me

How to Write a Program in Java to Calculate the Mean

Calculating Mean is very important in day-to-day life. Mean, or mean average, is used along with many other mathematical operations and is an important thing to know. But, if we are dealing with big numbers, it becomes easier to use a program. Here is how you can write your own Java program to calculate mean.

Steps

  1. How.com.vn English: Step 1 Plan your program...
    Plan your program. Planning your program is essential. Think about where your program will be used. Is the program going to deal with very big numbers? If yes, you may want to consider using data types like long instead of int.
    • Try to calculate the mean of a few numbers manually. This will help you understand your program.
  2. How.com.vn English: Step 2 Write the code...
    Write the code. To calculate the mean, you'll need the following parameters:
    • The sum of all the inputs provided by the user; and,
    • The total number of inputs provided by the user.
      • For example, if the sum of the inputs = 100, and the total number of inputs = 10, the mean = 100 / 10 = 10
    • Therefore, the formula to calculate the mean, or the average, is:

      Mean = Sum of all inputs / Total Number of inputs
    • To get these parameters (inputs) from the user, try using the Scanner function in Java.
      • You'll need to get multiple inputs from the user for each of the terms you want to find the mean of. Try using a loop for this. In the sample code below, a for loop is used. You can try using a while loop too.
  3. How.com.vn English: Step 3 Calculate the mean.
    Using the formula given in the previous step, write the code to calculate the mean. Make sure that the variable used for storing the value of mean is of type float. If not, the answer may not be correct.
    • This is because, the float data-type is 32 bit single precision that even considers decimals in mathematical calculations. Thus, using a float variable, the answer for a mathematical calculation like 5 / 2 (5 divided by 2) will be 2.5
      • If the same calculation (5 / 2) if done using an int variable, the answer will be 2.
      • However, the variables in which you stored the sum and number of inputs can be int. Using a float variable for the mean will automatically convert the int to float; and the total calculation will be done in float instead of int.
  4. How.com.vn English: Step 4 Display the result.
    Once the program has calculated the mean, display it to the user. Use the System.out.print or System.out.println (to print on a new line) function, in Java, for this.
    Advertisement


Community Q&A

Search
Add New Question
  • Question
    How do I write a Java program that computes tax on a user's income?
    How.com.vn English: Pingu
    Pingu
    Top Answerer
    First, you need to inform yourself about your local tax regulations, i.e. what percentage of taxes is on what kind of income. Some countries also have different taxes depending on life situation (how many children, whether the user is married, etc.). Then, you need to get the relevant information from the user. You may want to write a GUI for this. Calculate the taxes based on this information. Taxes are often specified in percent, but if you divide the percent number by 100, you get what number to multiply with. Print the output with System.out.println or with the function in your GUI. That'll be a complex program, so prepare to invest time and effort.
  • Question
    How would I write a function equivalent to (sum(x-mean(x)^2)) in a language like Java or C?
    How.com.vn English: Community Answer
    Community Answer
    Make your function so it takes in an array as a parameter. Then loop through the array, adding each value to the total. Finally, divide by array.length.
  • Question
    How can I write a program to calculate the average of integers given in a text field where each line in a text field contains a single integer? The average and number of integers in a file should be displayed within the applet.
    How.com.vn English: Community Answer
    Community Answer
    You've got to read the file, convert it into data, calculate the info, and display it. To read the file, try using a BufferedReader. To store the data, you may want to use an ArrayList, or any kind of variable-length list, so that you can extend it as you read the file. To convert from a String to an Integer, you can use Integer.valueOf(s). The code may look like:BufferedReader reader = ... ;ArrayList data = new ArrayList();String line = reader.readLine();while(line != null){ data.add(Integer.valueOf(line)); line = reader.readLine();}Calculating the values should be easy from here, and displaying them in an applet is up to you.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit

      Advertisement

      Sample Code

      import java.util.Scanner;public class main_class {    public static void main(String[] args){      int sum = 0, inputNum;      int counter;      float mean;      Scanner NumScanner = new Scanner(System.in);      Scanner charScanner = new Scanner(System.in);            System.out.println("Enter the total number of terms whose mean you want to calculate");      counter = NumScanner.nextInt();            System.out.println("Please enter " + counter + " numbers:");            for(int x = 1; x<=counter ;x++){                    inputNum = NumScanner.nextInt();          sum = sum + inputNum;          System.out.println();      }            mean = sum / counter;      System.out.println("The mean of the " + counter + " numbers you entered is " + mean);    }}
      import java.util.Scanner;/* *This implementation allows for the user to continuously enter *numbers until they have entered all of the necessary numbers. *The sentinel string is used so that the program can determine *when the user is done entering inputs. The function *Integer.parseInt(String s) takes a string and returns the number *that the string represents (i.e. Integer.parseInt("462")==462). * *One important note: when using this method for variable inputs, *one should not compare strings with "==" or "!=". This causes *the strings to be compared based on their location in memory. *s.equals(String t) returns true is the contents of each string *are the same. !s.equals(String t) returns true if the contents *are different. */public class main_class {    public static void main(String[] args){      String sentinel = "";      int sum = 0;      int counter = 0;      double mean = 0.0;      Scanner NumScanner = new Scanner(System.in);            System.out.println("Enter numbers to add. Enter \"d\" when done.");            System.out.print("Enter number: ");      sentinel = NumScanner.next();      System.out.println();      while(!sentinel.equals("d") && !sentinel.equals("D")) {           sum += Integer.parseInt(sentinel);           counter++;           System.out.print("Enter number: ");           sentinel = NumScanner.next();           System.out.println();      }      mean = (sum*1.0)/counter;      System.out.println();      System.out.println("The arithmetic mean is: " + mean +".");    }}

      Tips

      • Try expanding your program to perform multiple mathematical calculations.
      • Try making a GUI, which will make the program much more interactive and easier to use.
      Advertisement

      About this article

      How.com.vn is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, volunteer authors worked to edit and improve it over time. This article has been viewed 123,271 times.
      How helpful is this?
      Co-authors: 6
      Updated: April 5, 2018
      Views: 123,271
      Thanks to all authors for creating a page that has been read 123,271 times.

      Is this article up to date?

      ⚠️ Disclaimer:

      Content from Wiki How English language website. Text is available under the Creative Commons Attribution-Share Alike License; additional terms may apply.
      Wiki How does not encourage the violation of any laws, and cannot be responsible for any violations of such laws, should you link to this domain, or use, reproduce, or republish the information contained herein.

      Notices:
      • - A few of these subjects are frequently censored by educational, governmental, corporate, parental and other filtering schemes.
      • - Some articles may contain names, images, artworks or descriptions of events that some cultures restrict access to
      • - Please note: Wiki How does not give you opinion about the law, or advice about medical. If you need specific advice (for example, medical, legal, financial or risk management), please seek a professional who is licensed or knowledgeable in that area.
      • - Readers should not judge the importance of topics based on their coverage on Wiki How, nor think a topic is important just because it is the subject of a Wiki article.

      Advertisement