For each loop set value - java

Running into a problem. I have two methods with for each loops that calculates executives pay either by percentage or base pay. In my Executive class I have my pay method that takes base pay rate and multiplies with bonus. This works if it's percentage but if its base pay and call this method doesn't work.
Do I have put a if statement in my executive class to see if it's percentage or base pay?
Staff Class
/**
* Assigns the specified flat value weekly bonus to the Executives.
*
* #param bonusValue
* as a double, i.e., $1,000 = 1000.0
*/
public void setExecutiveBonusFlatRate(double bonusValue) {
for (StaffMember executiveEmployee : staffList) {
if (executiveEmployee instanceof Executive) {
((Executive) executiveEmployee).setBonus(bonusValue);
}
}
}
/**
* Assigns the specified percentage weekly bonus to the Executives.
*
* #param bonus
* as a percentage, i.e., 20% = 0.2
*/
public void setExecutiveBonusPercentage(double bonusPercentage) {
for (StaffMember executiveEmployee : staffList) {
if (executiveEmployee instanceof Executive) {
((Executive) executiveEmployee).setBonus(bonusPercentage);
}
}
}
/**
* Pays all the staff members.
*/
public void payday() {
for (StaffMember allEmployee : staffList) {
allEmployee.toString();
System.out.println(allEmployee.pay());
System.out.println(allEmployee.toString());
}
}
From Executive class extended from Employee
/** #overide
* return the weekly payrate plus the bonus
*/
public double pay() {
double payment = payRate * bonus;
bonus = 0;
return payment;

We need to correct two things here:
setExecutiveBonusPercentage should set the bonus as base * percentage * 0.01 to be consistent with bonusValue set in setExecutiveBonusFlatRate as we have no way to know whether bonus is a value or percentage.
In pay() method, we are setting bonus to 0 (bonus = 0;) which needs to be removed as it resets the bonus value. Due to this, first call of pay() will return correct result whereas subsequent calls will return 0.

Related

How do you put integers within a range in Java?

Though I am sure that this answer is simple, I am not sure that is asked of me for this assignment. Here is the full code that I have written (so just a return!) as well as the instructions that were given:
package code;
/**
* This class contains a variety of methods that will be used throughout the Ratings and Reviews
* project.
*/
public class Utilities{
/**
* Computes the average of two ratings
*
* #param rating0 An integer rating in the range of 1-5 inclusive
* #param rating1 An integer rating in the range of 1-5 inclusive
* #return the average of rating0 and rating1 as a double
*/
public double averageRating(int rating0, int rating1){
return ((rating0 + rating1) / 2); // Don't forget to replace this return statement with your own
}
Sorry for bad structure upon pasting it. I think my return is suitable for what is being done, provided that the rating could be just anything. I know that it can only be between 1-5, though, so how would one go about specifying that?
How about throwing an InvalidArgumentException if the range is violated?
e.g.
public double averageRating(int rating0, int rating1){
if (rating0 < 1 || rating0 > 5 || rating1 < 1 || rating1 > 5) {
throw new InvalidArgumentException("Rating out of range");
}
return ((rating0 + rating1) / 2.0); // Don't forget to replace this return statement with your own
}

Getting the unicode value of the first character in a string

I am basically being asked to take the Unicode value of a string, multiply it by 10% and add whatever level the object currently has. It's frustrating because as it turns out I have the logic down including the code yet I still get an error that says: expected:<0> but was:<8>. Any suggestions, maybe it's just a slight nuance I have to make in the logic, although I'm fairly certain it's right. Take note of the getLevel method because that's where the error is
public class PouchCreature implements Battleable {
private String name;
private int strength;
private int levelUps;
private int victoriesSinceLevelUp;
/**
* Standard constructor. levelUps and victoriesSinceLevelUp start at 0.
*
* #param nameIn desired name for this PouchCreature
* #param strengthIn starting strength for this PouchCreature
*/
public PouchCreature(String nameIn, int strengthIn) {
this.name = nameIn;
this.strength = strengthIn;
this.levelUps = 0;
this.victoriesSinceLevelUp = 0;
}
/**
* Copy constructor.
*
* #param other reference to the existing object which is the basis of the new one
*/
public PouchCreature(PouchCreature other) {
this.name=other.name;
this.strength=other.strength;
this.levelUps=other.levelUps;
this.victoriesSinceLevelUp=other.victoriesSinceLevelUp;
}
/**
* Getter for skill level of the PouchCreature, which is based on the
* first character of its name and the number of levelUps it has.
* Specifically, the UNICODE value of the first character in its name
* taken %10 plus the levelUps.
*
* #return skill level of the PouchCreature
*/
public int getLevel() {
int value = (int)((int)(getName().charAt(0)) * 0.1);
return value + this.levelUps;
}
You've said you're supposed to increase the value by 10%. What you're actually doing, though, is reducing it 90% by taking just 10% of it (and then truncating that to an int). 67.0 * 0.1 = 6.7, which when truncated to an int is 6.
Change the 0.1 to 1.1 to increase it by 10%:
int value = (int)((int)(getName().charAt(0)) * 1.1);
// --------------------------------------------^
There, if getName() returns "Centaur" (for instance), the C has the Unicode value 67, and value ends up being 73.
We need to see the code you're calling the class with and that is generating your error message. Why is it expecting 0? 8 seems like a valid return value from the information you've given.

Java car class for beginner

I must Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles/gallon or liters/km—pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor, and the initial fuel level is 0. Supply a method drive that simulates driving the car for a certain distance, reducing the amount of gasoline in the fuel tank. Also supply methods getGasInTank, returning the current amount of gasoline in the fuel tank, and addGas, to add gasoline to the fuel tank.
I have created a class for the car and a test program to plug some values in and when i run the program all i get returned is the addGas value that i put in. the computation for the miles per gallon will not run and i do not understand why. as you can probably tell i am VERY new at java and any help on the issue is much appreciated.
public class CarTest
{
public static void main(String[] args)
{
Car richCar = new Car(49);
richCar.addGas(15);
richCar.drive(150);
System.out.println(richCar.getGas());
}
}
/**
A car can drive and consume fuel
*/
public class Car
{
/**
Constructs a car with a given fuel efficiency
#param anEfficiency the fuel efficiency of the car
*/
public Car(double mpg)
{
milesPerGallon = mpg;
gas = 0;
drive = 0;
}
/** Adds gas to the tank.
#param amount the amount of fuel added
*/
public void addGas(double amount)
{
gas = gas + amount;
}
/**
Drives a certain amount, consuming gas
#param distance the distance driven
*/
public void drive(double distance)
{
drive = drive + distance;
}
/**
Gets the amount of gas left in the tank.
#return the amount of gas
*/
public double getGas()
{
double mpg;
double distance;
distance = drive;
mpg = gas * milesPerGallon / distance;
return gas;
}
private double drive;
private double gas;
private double milesPerGallon;
}
Combining some ideas...
/**
Drives a certain amount, consuming gas
#param distance the distance driven
*/
public void drive(double distance)
{
drive = drive + distance;
gas = gas - (distance / milesPerGallon);
}
/**
Gets the amount of gas left in the tank.
#return the amount of gas
*/
public double getGas()
{
return gas;
}
Your test program only calls three methods:
richCar.addGas(15);
richCar.drive(150);
System.out.println(richCar.getGas());
Let's take a look at what each one does.
addGas(15) modifies your gas instance variable.
drive(150) only executes the line drive = drive + distance;
getGas() seems to do a couple things, more than expected (one would expect it just returns gas but it also calculates and stores latest mpg value). But if you check the code of getGas() gas is never modified, only returned.
So you called three methods, and within those three executions gas is only modified once, when you set it to the value of 15 with richCar.addGas(15).
It would seem most simple if the drive(int) method modifys gas based on some set mpg value, instead of only keeping track of how many miles were driven, and then you could have drive() simply just return gas.
That means you would also get rid of modifying mpg in getGas(), which is good, because that value is needed no matter what to calculate how much gas is used. You could perhaps introduce a actualMpg value if you had some more logic that changed how much gas is used but you don't have that yet.
It's computing it just fine. Your method is only returning the one value for gas, though.
This could use some clean-up; I'd suggest getting rid of all of the cruft, and just returning the calculation.
public double calculateGas() {
return (gas * milesPerGallon) / drive;
}
From what it looks like your problem lies here
public double getGas()
{
double mpg;
double distance;
distance = drive;
mpg = gas * milesPerGallon / distance;
return gas;
}
you are doing a calculation to mpg however you are returning the gas property at the end.
It doesn't actually seem like you are changing the value of gas anywhere except for when you first add it.

Public class DiscoLight help

If some one can point me in the right direction for this code for my assigment I would really appreciate it.
I have pasted the whole code that I need to complete but I need help with the following method public void changeColour(Circle aCircle) which is meant to allow to change the colour of the circle randomly, if 0 comes the light of the circle should change to red, 1 for green and 2 for purple.
public class DiscoLight
{
/* instance variables */
private Circle light; // simulates a circular disco light in the Shapes window
private Random randomNumberGenerator;
/**
* Default constructor for objects of class DiscoLight
*/
public DiscoLight()
{
super();
this.randomNumberGenerator = new Random();
}
/**
* Returns a randomly generated int between 0 (inclusive)
* and number (exclusive). For example if number is 6,
* the method will return one of 0, 1, 2, 3, 4, or 5.
*/
public int getRandomInt(int number)
{
return this.randomNumberGenerator.nextInt(number);
}
/**
* student to write code and comment here for setLight(Circle) for Q4(i)
*/
public void setLight(Circle aCircle)
{
this.light = aCircle;
}
/**
* student to write code and comment here for getLight() for Q4(i)
*/
public Circle getLight()
{
return this.light;
}
/**
* Sets the argument to have a diameter of 50, an xPos
* of 122, a yPos of 162 and the colour GREEN.
* The method then sets the receiver's instance variable
* light, to the argument aCircle.
*/
public void addLight(Circle aCircle)
{
//Student to write code here, Q4(ii)
this.light = aCircle;
this.light.setDiameter(50);
this.light.setXPos(122);
this.light.setYPos(162);
this.light.setColour(OUColour.GREEN);
}
/**
* Randomly sets the colour of the instance variable
* light to red, green, or purple.
*/
public void changeColour(Circle aCircle)
{
//student to write code here, Q4(iii)
if (getRandomInt() == 0)
{
this.light.setColour(OUColour.RED);
}
if (this.getRandomInt().equals(1))
{
this.light.setColour(OUColour.GREEN);
}
else
if (this.getRandomInt().equals(2))
{
this.light.setColour(OUColour.PURPLE);
}
}
/**
* Grows the diameter of the circle referenced by the
* receiver's instance variable light, to the argument size.
* The diameter is incremented in steps of 2,
* the xPos and yPos are decremented in steps of 1 until the
* diameter reaches the value given by size.
* Between each step there is a random colour change. The message
* delay(anInt) is used to slow down the graphical interface, as required.
*/
public void grow(int size)
{
//student to write code here, Q4(iv)
}
/**
* Shrinks the diameter of the circle referenced by the
* receiver's instance variable light, to the argument size.
* The diameter is decremented in steps of 2,
* the xPos and yPos are incremented in steps of 1 until the
* diameter reaches the value given by size.
* Between each step there is a random colour change. The message
* delay(anInt) is used to slow down the graphical interface, as required.
*/
public void shrink(int size)
{
//student to write code here, Q4(v)
}
/**
* Expands the diameter of the light by the amount given by
* sizeIncrease (changing colour as it grows).
*
* The method then contracts the light until it reaches its
* original size (changing colour as it shrinks).
*/
public void lightCycle(int sizeIncrease)
{
//student to write code here, Q4(vi)
}
/**
* Prompts the user for number of growing and shrinking
* cycles. Then prompts the user for the number of units
* by which to increase the diameter of light.
* Method then performs the requested growing and
* shrinking cycles.
*/
public void runLight()
{
//student to write code here, Q4(vii)
}
/**
* Causes execution to pause by time number of milliseconds
*/
private void delay(int time)
{
try
{
Thread.sleep(time);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
You have forgotten to pass a parameter when calling getRandomInt() in the very first line below //student to write code here. Your compiler should already point this out, though.
The documentation comment above the getRandomInt() method tells you what it expects as parameter, and what you can expect as return value.
Also, if you want equal chances that the lamp is red, green or purple, you should be able to do that with a single invocation of getRandomInt(). Store the value in a variable, and use a switch statement to turn on the correct light:
int randomValue = getRandomInt(/* I am not telling you what to put here */);
switch (randomValue) {
case 0: light.setColour(OUColour.RED); break;
case 1: light.setColour(OUColour.GREEN); break;
case 2: light.setColour(OUColour.PURPLE); break;
}
/**
* Randomly sets the colour of the instance variable
* light to red, green, or purple.
*/
public void changeColour(Circle aCircle)
{
int i = getRandomInt(3);
if (i == 0)
{
this.light.setColour(OUColour.RED);
}
else if (i == 1)
{
this.light.setColour(OUColour.GREEN);
}
else
{
this.light.setColour(OUColour.PURPLE);
}
}
the method getRandomInt returns an int, so you can't use equals to compare. use:
if (getRandomInt(3) == 1) {
...
}
and you just need to call it once. store the random integer in a variable and compare its value with the ones you want.
you're calling getRandomInt several times, with each time a new (random) value returned.
you should call it once at the begin of the method, and then check if it is 0,1 or 2.
Regards
Guillaume

Trend analysis using iterative value increments

We have configured iReport to generate the following graph:
The real data points are in blue, the trend line is green. The problems include:
Too many data points for the trend line
Trend line does not follow a Bezier curve (spline)
The source of the problem is with the incrementer class. The incrementer is provided with the data points iteratively. There does not appear to be a way to get the set of data. The code that calculates the trend line looks as follows:
import java.math.BigDecimal;
import net.sf.jasperreports.engine.fill.*;
/**
* Used by an iReport variable to increment its average.
*/
public class MovingAverageIncrementer
implements JRIncrementer {
private BigDecimal average;
private int incr = 0;
/**
* Instantiated by the MovingAverageIncrementerFactory class.
*/
public MovingAverageIncrementer() {
}
/**
* Returns the newly incremented value, which is calculated by averaging
* the previous value from the previous call to this method.
*
* #param jrFillVariable Unused.
* #param object New data point to average.
* #param abstractValueProvider Unused.
* #return The newly incremented value.
*/
public Object increment( JRFillVariable jrFillVariable, Object object,
AbstractValueProvider abstractValueProvider ) {
BigDecimal value = new BigDecimal( ( ( Number )object ).doubleValue() );
// Average every 10 data points
//
if( incr % 10 == 0 ) {
setAverage( ( value.add( getAverage() ).doubleValue() / 2.0 ) );
}
incr++;
return getAverage();
}
/**
* Changes the value that is the moving average.
* #param average The new moving average value.
*/
private void setAverage( BigDecimal average ) {
this.average = average;
}
/**
* Returns the current moving average average.
* #return Value used for plotting on a report.
*/
protected BigDecimal getAverage() {
if( this.average == null ) {
this.average = new BigDecimal( 0 );
}
return this.average;
}
/** Helper method. */
private void setAverage( double d ) {
setAverage( new BigDecimal( d ) );
}
}
How would you create a smoother and more accurate representation of the trend line?
This depends on the behavior of the item you are measuring. Is this something that moves (or changes) in a manner that can be modeled?
If the item is not expected to change, then your trend should be the underlying mean value of the entire sample set, not just the past two measurements. You can get this using Bayes theorem. The running average can be calculated incrementally using the simple formula
Mtn1 = (Mtn * N + x) / (N+1)
where x is the measurement at time t+1, Mtn1 is the mean a time t+1, Mtn is the mean at time t, and N is the number of measurements taken by time t.
If the item you are measuring fluctuates in a manner that can be predicted by some underlying equation, then you can use a Kalman filter to provide a best estimate of the next point based on the previous (recent) measurements and the equation that models the predicted behavior.
As a starting point, the Wikipedia entry on Bayesian estimators and Kalman Filters will be helpful.
Resulting Image
The result is still incomplete, however it clearly shows a better trend line than that in the question.
Calculation
There were two key components missing:
Sliding window. A List of Double values that cannot grow beyond a given size.
Calculation. A variation on the accept answer (one less call to getIterations()):
((value - previousAverage) / (getIterations() + 1)) + previousAverage
Source Code
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import net.sf.jasperreports.engine.fill.AbstractValueProvider;
import net.sf.jasperreports.engine.fill.JRFillVariable;
import net.sf.jasperreports.engine.fill.JRIncrementer;
/**
* Used by an iReport variable to increment its average.
*/
public class RunningAverageIncrementer
implements JRIncrementer {
/** Default number of tallies. */
private static final int DEFAULT_TALLIES = 128;
/** Number of tallies within the sliding window. */
private static final int DEFAULT_SLIDING_WINDOW_SIZE = 30;
/** Stores a sliding window of values. */
private List<Double> values = new ArrayList<Double>( DEFAULT_TALLIES );
/**
* Instantiated by the RunningAverageIncrementerFactory class.
*/
public RunningAverageIncrementer() {
}
/**
* Calculates the average of previously known values.
* #return The average of the list of values returned by getValues().
*/
private double calculateAverage() {
double result = 0.0;
List<Double> values = getValues();
for( Double d: getValues() ) {
result += d.doubleValue();
}
return result / values.size();
}
/**
* Called each time a new value to be averaged is received.
* #param value The new value to include for the average.
*/
private void recordValue( Double value ) {
List<Double> values = getValues();
// Throw out old values that should no longer influence the trend.
//
if( values.size() > getSlidingWindowSize() ) {
values.remove( 0 );
}
this.values.add( value );
}
private List<Double> getValues() {
return values;
}
private int getIterations() {
return getValues().size();
}
/**
* Returns the newly incremented value, which is calculated by averaging
* the previous value from the previous call to this method.
*
* #param jrFillVariable Unused.
* #param tally New data point to average.
* #param abstractValueProvider Unused.
* #return The newly incremented value.
*/
public Object increment( JRFillVariable jrFillVariable, Object tally,
AbstractValueProvider abstractValueProvider ) {
double value = ((Number)tally).doubleValue();
recordValue( value );
double previousAverage = calculateAverage();
double newAverage =
((value - previousAverage) / (getIterations() + 1)) + previousAverage;
return new BigDecimal( newAverage );
}
protected int getSlidingWindowSize() {
return DEFAULT_SLIDING_WINDOW_SIZE;
}
}

Categories