Keeping a running average of values in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I am trying to calculate the average of values given via repeated function calls.
Actually Bluej allows me to put the number to rate but if i am trying to put again it replaces the previous one, i want to be stored and after that an average to be shown.
I can't figure out how to do it
This is the part of code:
public int getRate() // here i put an int number
{
return this.rate;
}
public void setRate(int rate) // here i change it but i think i don't need it
{
this.rate = rate;
}
I can't use strange or complex commands because i am allowed to only use this type of commands like get/set and arraylists.
It is a school assignment.
Thanks

An easy way to keep an average of inputs is to keep track of:
The sum of all inputs received so far.
The number of inputs you have received.
Every time you call setRate to update the rate, you add to the sum and increment the count. You also need a special case for when no rates have been added yet, to avoid division by zero:
private int ratesSum = 0;
private int rateCount = 0;
public int getRate()
{
return this.rate;
}
public void setRate(int rate)
{
this.rate = rate;
this.ratesSum += rate;
this.rateCount++;
}
// Gets the average of all rates so far, or returns zero if no rates
// have been set yet.
public float getAverageRate()
{
// Do not divide by zero
if (rateCount == 0) return 0;
return ((float)ratesSum) / ((float)rateCount);
}

Related

What is the reason behind this kind of error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm very new to programming and I've been teaching myself for almost a month now, can someone please explain to methe reason behind error in my code? It errors in the "total(moneyConv(moneySum * moneyRate));" line,
saying actual and formal argument differs in length. I've check all my parameters and it seemed fine to me. thanks a lot!
public class NewClass {
static Scanner sc = new Scanner(System.in);
public static float moneySum;
public static float moneyRate;
public static void findSum(float sum) {
moneySum = sum;
}
public static void findRate(float rate) {
moneyRate = rate;
}
public static float moneyConv(float sum, float rate) {
return sum * rate;
}
public static void total(float total) {
System.out.println(total + "Here is the total of your transaction.");
}
public static void main(String[] args) {
System.out.print("Input amount of money : ");
findSum(sc.nextFloat());
System.out.print("Input exchange rate : ");
findRate(sc.nextFloat());
total(moneyConv(moneySum * moneyRate));
}
the moneyConv() method parameters have 2 arguments: a float datatype sum and another float datatype rate. When you look at the method call:
total(moneyConv(moneySum * moneyRate));
you are actually trying to call the method moneyConv(float sum, float rate) but with one argument instead with a float datatype, as a result of the multiplication of moneySum and moneyRate. This is not valid since moneyConv accepts 2 arguments.
So, the fix would be total(moneyConv(moneySum, moneyRate));
First the nested method moneyConv(moneySum,moneyRate) will be executed and after the method total will be executed with the result of the moneyConv method.
Method parameters must be separated by commas:
total(moneyConv(moneySum, moneyRate));
moneySum * moneyRate is first evaluated and becomes a single value which is passed to moneyConv which actually requires two arguments.
It is equivalent to:
float temporary = moneySum * moneyRate;
total(moneyConv(temporary))

Homework: Magic Plant Recursion Exercise in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
To make it clear, this IS a graded assignment for my Programming II class. I've generally been very easily receptive to new programming concepts but this particular assignment on recursion is really throwing me and I'm looking for some good nudging in the right direction. Below is the assignment verbatim and the code I currently already have.
Magic Plant
We have a magic plant that once it is planted, it germinates and grows two leaves in the first year. It doubles its leaves every year except that every three years it triples its leaves. Something like:
Write a class called MagicPlant that includes the following methods:
A method that returns the number of leaves given the age of the plant
A non-recursive method that returns the age of the plant given the number of leaves.
A recursive method that returns the age of the plant given the number of leaves.
In a driver class test the methods.
Find out what is the largest (oldest) plant that your algorithm and data structure can handle.
That is what I was given and I'm having trouble on the last bullet point as well as a bit muddy on the second one (but I have code that seems to work).
My current code excluding the Driver class since it's just call statements:
public class MagicPlant {
// Method that returns the number of leaves given
// the age of the plant.
public int getLeaves(int age) {
int leafCount = 1;
for (int i = 1; i <= age; i++) {
if (i % 3 != 0) {
leafCount *= 2;
} else {
leafCount *= 3;
}
}
return leafCount;
}
// Non-recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeNR(int leaves) {
int age = 1;
while (leaves > getLeaves(age)) {
age++;
}
return age;
}
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
return 0;
}
}
My tipp is, to replace the while-loop with recursion. So you don't have a local variable but instead give that variable back into the method (recursive).
Also i would suggest that you make 2 methods for the recursion:
public int getAgeR(int leaves){
return getAgeR(1, leaves); // call overload with initial value
}
private int getAgeR(int age, int leaves){
// do your magic here
}
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
if(leaves == 2) {
return 1;
}
if(leaves % 3 == 0) {
return getAgeR(leaves/3)+1;
} else {
return getAgeR(leaves/2)+1;
}
}
It's the inverse of counting years. Instead of starting from the beginning, you just have to start from the end and decreasing for every recurrent loop.

Beginner Java Issues [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
EDIT: I am using BlueJ. When I right click my class I am supposed to enter the values for a and b there rather than the actual code. Is there a way to do that?
Hello I am trying to write a basic program that will let me enter 2 numbers and then automatically calculate the sum, difference, division and remainder, and then print the results to the output. Here is what I have so far. It compiles but I get this error
java.lang.ArithmeticException: / by zero
at Q1A3.DoTheCalculation(Q1A3.java:33)
at Q1A3.<init>(Q1A3.java:24)
when I try to run it. I have no java experience and this is my first time trying anything on the computer other than emailing. Please be gentle! Can you point out my errors and guide me toward fixing them? Thank you.
/*
This program accepts two numbers from the user. Finds out the sum, diff, division and
remainder of the two numbers, and prints the results on the screen
*/
public class Q1A3
{
//instant variables - replace the example below with your own
private int a;
private int b;
private int sum;
private int difference;
private int division;
private int remainder;
//-----------------------------------------
//The following is the constructor that takes the input from the user
//and stores it in the system
public Q1A3(int a, int b)
{
DoTheCalculation ( );
PrintTheResults ( );
}
//-------------------------------------------------------------
//The following routine does all of the required calculations.
public void DoTheCalculation ( )
{
sum = (a+b);
difference = (a-b);
division = (a/b);
remainder = (a%b);
}
//----------------------------------------------------------------------------
//The following routine prints all of the information including the calculated
//items on the screen
public void PrintTheResults ( )
{
System.out.println("The value of “a” is:");
System.out.println("The value of “b” is:");
System.out.println("The sum is:" );
System.out.println("The difference is:");
System.out.println("The division is:");
System.out.println("The remainder is:");
}
}
You don't assign any values to a or b. try this:
private int a = 5;
private int b = 7;
(1) Make sure that private member variables are initialized from constructor parameters.
(2) Make sure to assign variables to string outputs.
Please observe the proposed changes in the following source code:
public Q1A3(int a, int b)
{
this.a = a;
this.b = b;
DoTheCalculation ( );
PrintTheResults ( );
}
public void PrintTheResults ( )
{
System.out.println("The value of 'a' is:"+a);
System.out.println("The value of 'b' is:"+b);
System.out.println("The sum is:" +sum);
System.out.println("The difference is:"+difference);
System.out.println("The division is:"+division);
System.out.println("The remainder is:"+remainder);
}
public static void main(String [] args)
{
Q1A3 obj = new Q1A3(8,4);
}
Your answer is in the first line of the error code "/ by zero". You cannot divide by zero (it'd implode the universe or something.) Try an if statement to test if 0 is being passed, and reject, or skip it.
You cannot divide by zero (it'd implode the universe or something.)
~ Andrew
No, it creates black holes. Or something :P
The question has been answered. BUT:
A good way to find the mistake yourself (next time) would have been a good debugger or systematic outputs, e.g. System.out.println("var a:"+a) to see what values which variables have at the time, before the error occurs.

understanding the meaning of varying [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Write a method to calculate the monthly payments you would have to make over a given number of years to pay off a loan at a given interest rate compounded continuously. The method takes the number of years t, the principal P, and the annual interest rate r as arguments. The desired value is given by the formula (P ert/ 12 t). Use Math.exp(). The signature of the method should be: public static double monthlyPayment(double years, double principal, double rate) Use the method to write a program Payments that generates a set of the monthly payments one would have to make for a $20,000 loan over 5 years at interest rates varying from 5% to 8% in 0.25% increments.
public class Payments {
public static void main(String[] args) {
for(double r=0.05; r<=0.08; r+=0.0025) {
System.out.println(monthlyPayment(5,20000,r));
}
}
public static double monthlyPayment(double years,double principal,double rate) {
return ((principal*(Math.exp(years*rate)))/(12*years));
}
}
This is what I wrote so far and I'm not sure what to do actually, I don't understand by what the mean by varying from 5% to 8% in 0.25% increment ! Can anybody explain please ?
The question is telling you to create a table for
5.00%
5.25%
...
...
7.75%
8.00

How to loop through an array to find the closest distance? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm stuck trying to figure out how to loop through an array of zip codes and find the closest zip code to a target. The zip codes also contain their latitude and longitude which is used to calculate the distance to the target. I need figure out how to loop through the array storing the closest distance and then returning the zip code of the closest one. Any help would be great because I've tried everything I can think of.
* Finds and returns the zip code of a postal zone in the collection
* whose centroid is closest to a given location.
*
* #param target the target location.
*
* #return returns zipCode of the postal zone whose centroid is closest;
* returns COLLECTION_EMPTY if no zones are in the collection.
*/
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation()
.calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i]
.getZoneLocation().calcDistance(target);
counter++;
return closeZip;
}
}
return closeZip;
}
According to doc:
A method returns to the code that invoked it when it
1. completes all the statements in the method,
2. reaches a return statement, or
3. throws an exception,
whichever occurs first.
It means that your code finishes its work after the first iteration. As far as I understand you want to find the closest one among array of zones.
I guess you don't need return inside loop. Please comment or delete it .
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation().calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i].getZoneLocation().calcDistance(target);
counter++;
// return closeZip;
}
}
return closeZip;
}

Categories