Function method for average numbers - java

public class Part4 {
public static void main(String args []) {
Random rand = new Random();
int total = 0;
for(int i = 0;i< 10;i++) {
total += rand.nextInt(101);
}
double avg = (double) total/10;
System.out.println("The average of 10 marks is " +avg);
}
}
My code works perfectly, however I don't know how to put my code in the procedure method. Can you please help me with that?

Do it like this. You can say with parameter amount with how many number you want to calculate the average.
public double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
System.out.println("The average of 10 marks is " + avg);
return avg;
}

The following example shows how to delegate the calculations to a method , how to call it by instantiating the class Part4
public class Part4
{
public double getAvgRandNum(int num)
{
Random rand = new Random();
int total = 0;
for(int i = 0;i< num ;i++)
{
total += rand.nextInt(101);
}
double avg = (double) total/num;
return avg;
}
public static void main(String args []) {
Part4 prt = new Part4()
double avgRes = prt.getAvgRandNum(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
In Main we are instantiating (creating an object of) class Part4.Once an object is created "prt" just use the dot operator to access (call) its method getAvgRandNum.

It seems like you're at a very early stage of learning Java, so I thought I'd pop in an even 'simpler' solution.
public class Part4
{
//This is the method you need to call
public static double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
return avg;
}
public static void main(String args []) {
//And this is how we call it
double avgRes = calculateAverage(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
Thanks to Moh123 and Mosa, I borrowed some code.

Related

Java average method stuck

So guys this is my code. the code runs fine but I don't get the proper average. Could someone please fix it.
import java.util.Scanner;
public class test {
public static double Avg(int amt, int num) {
int tot = 0;
tot = tot + num;
int average = tot/amt;
return average;
public static void main(String[] args) {
double average_ICT_01 = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> ICT_01 = new ArrayList<Integer>();
for (int i=0; i<3; i++) {
int num = sc.nextInt();
ICT_01.add(num);
}
int length01 = ICT_01.size();
for (int c=0; c<3; c++) {
int num1 = ICT_01.get(c);
average_ICT_01 = Avg(length01,num1);
}
System.out.println(average_ICT_01);
}
}
The arithmetic average of n numbers is their sum divided by n. So a method for calculating the average of all the numbers in a vector should be:
public static double avg(List<int> vec){
//Sum all numbers
long sum = 0;
for(int i=0;i<vec.size();i++){
sum = sum + vec.get(i);
}
//Divide by the number of numbers
double avg = sum/vec.size();
//Return the average
return avg;
}

Array Index Out of Bounds Exception in 1 of 3 Methods [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This should be a fairly simple homework assignment, but I've been pounding my face on it for a while now ... When executed, it should just populate an array and find the mean and standard deviation. I'm getting an out of bounds exception, but only in the arrayDeviation method. Any direction would be appreciated.
import java.util.Scanner;
import java.util.Random;
public class StandardDeviation
{
//declare global variables
final static int ELEMENTS = 100;
public static void main(String [] args)
{
//declare variables
final int RANGE = 500;
int[] numList = new int[ELEMENTS];
Random rand = new Random();
//populate array
for(int count = 0; count < ELEMENTS; count++)
{
numList[count] = rand.nextInt(RANGE) + 1;
}
//call printArray
printArray(numList);
//call arrayAverage
double mean = arrayAverage(numList);
System.out.println("\nMean: " + mean);
//call arrayDeviation
double standardDeviation = arrayDeviation(numList, mean);
System.out.print("Standard deviation: " + standardDeviation);
} //end main
//output 10 elements per line
public static void printArray(int[] list)
{
final int ELEMENTS_PER_LINE = 10;
for(int count = 0; count < ELEMENTS; count++)
{
System.out.printf("%-4d", list[count]);
if ((count + 1) % ELEMENTS_PER_LINE == 0)
{
System.out.println();
}
}
}
//returns average as double
public static double arrayAverage(int[] list)
{
int sum = 0, count;
double average;
for(count = 0; count < ELEMENTS; count++)
{
sum = sum + list[count];
}
average =(double) sum / count;
return average;
}
//calculate and return standard deviation
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++);
{
sum = sum + Math.pow((list[count] - mean), 2);
}
standardDeviation = Math.sqrt(sum / 2);
return standardDeviation;
}
} //end class
Staring at this code for like 10 minutes I couldn't see why it's giving that Exception.Pasting it in Netbeans and it instatly highlights an empty for-loop
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++); //This semicolon is your
//problem
{
sum = sum + Math.pow((list[count] - mean), 2);
}

How to assign last element in array as the result of a different method?

I've created two different methods that calculate random monthly savings, and the monthly interest on those savings and saves each to its own array. I would like to have a new method that returns the last element in the calculateInterest array (as its the cumulative total of savings and interest in a year), so i can use that specific number in a different part of my program later.
So her is what i have so far. My methods for calculating savings and interest work just fine but i don't know how to actually get the value and not just the array number (which is all I've been able to call) in my last method.
Any help or direction would be greatly appreciated!
public class EmployeeSavings extends AddressBook {
private double accountValue;
private double[] monthlyInterests = new double [12];
private double[] monthlySavings = new double[12];
private static final double MONTHLY_RATE= 0.00417;
public double[] generateMonthlySavings() {
double min = 100;
double max = 800;
double range = (max - min);
for (int i = 0; i < monthlySavings.length; i++) {
monthlySavings[i] = (Math.random() * range) + min;
System.out.println(monthlySavings[i]);
}
return monthlySavings;
}
public double[] calculateInterest() {
double count = 0;
for (int i = 0; i < monthlyInterests.length; i++) {
if (i <= monthlyInterests.length)
count = (monthlySavings[i] + count) * (1 + MONTHLY_RATE);
System.out.println(count);
}
return monthlyInterests;
}
public double[] getMonthlyInterest(){
return monthlyInterests;
}
public double[] getMonthlySavings() {
return monthlySavings;
}
// Would like to return total value here
public double getAccountValue() {
for (int i = 12; i <= getMonthlyInterest().length; i++) {
accountValue = i;
}
return accountValue;
}
If your java version is 8 I would do it like so
public double getAccountValue() {
return DoubleStream.of( getMonthlyInterest() ).sum();
}
It's much shorter and I think it's also more readable. But if your java version isn't 8 do something like this
double[] d = getMonthlyInterest();
double value = 0d;
for (int i = 0; i < d.length; i++) {
value += d[i]; // d[i] returns value which has i index in array d.
}

How do I get the Average Method to give correct output in Java

I am expecting 3.5 as result from average method, but I get 3.0. No idea why. I expected Double to give me the result, but no.
java.util.ArrayList;
public class Hangman {
public static void main(String[] args) {
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(3);
intList.add(2);
intList.add(7);
intList.add(2);
System.out.println("The variance number is : ");
System.out.println(sum(intList));
System.out.println(intList.size());
System.out.println(average(intList));
}
public static int sum(ArrayList<Integer> intList) {
int sum = 0;
for (int counter = 0; counter < intList.size(); counter++) {
sum = sum + intList.get(counter);
}
return sum;
}
public static double average(ArrayList<Integer> intList) {
double avg = sum(intList) / (intList.size());
return avg;
}
public static ArrayList<Double> subtract(ArrayList<Integer> intList) {
ArrayList<Double> subtracted = new ArrayList<Double>();
for (double subtract : intList) {
subtracted.add((double) (subtract - average(intList)));
}
return subtracted;
}
public static double variance(ArrayList<Integer> intList) {
double sumDiffsSquared = 0.0;
double avg = average(intList);
for (int value : intList) {
double diff = value - avg;
diff *= diff;
sumDiffsSquared += diff;
}
return (sumDiffsSquared / (intList.size() - 1));
}
}
sum needs to return a double, otherwise when you do a
sum(intList) / (intList.size());
in your average method, it truncates the value calculated down to an integer, and then puts that value in double form.
Your function needs to return a double value.
Change your method to
public static double sum(ArrayList<Integer> intList) {
double sum = 0;
for (int counter = 0; counter < intList.size(); counter++) {
sum = sum + intList.get(counter);
}
return sum;
}
and you should be doing fine.
Though the type of avg is double , sum() method is returning a Integer value. So you have return a double from sum() method
double avg = (double)sum(intList) / (intList.size());

The mean and the standard deviation of the values in its array parameter

Here's My Code; and I can find an array with this and I would like to calculate the mean of the values (overall) after this I would like to calculate standard deviation of this but I couldn't understand the question exactly so I dont have a method for now. Here's the question for standard deviation (Write a method that takes two parameters --a set of int values in an array and a double value representing their mean-- and computes and returns the standard deviation of the values using the given mean.)
import java.util.*;
public class Test
{
final static int N = 100;
static int limit = 0;
static int[] list;
static int i, j;
static int sum = 0;
static Scanner scan = new Scanner (System.in);
public static int[] generateArray ()
{
System.out.print ("Enter your array limit: ");
limit = scan.nextInt();
list = new int[limit];
for(i = 0; i < limit; i++)
{
list[i] = (int) (Math.random() * 2 * N - N);
}
return list;
}
public static void printArray()
{
for(j = 0; j < limit; j++)
System.out.print (list[j] + "\t");
}
public static void meanArray()
{
sum = sum + list[j]; //PROBLEM HERE
System.out.println (sum);
}
public static void main(String[] args)
{
generateArray();
printArray();
meanArray(); //PROBLEM HERE
}
}
To generate the mean value, add up all values in your list and devide them by the number of values:
public static void meanArray() {
double result = 0;
for(int i : list) {
result += i;
}
result /= list.length;
System.out.println(result);
}

Categories

Resources