Public class DiscoLight help - java

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

Related

How can I test if the LTrigger or RTrigger from Xbox controller is pressed in java?

So I am trying to check if the LTrigger or the RTrigger is pressed. Here is what I am trying to do.
public double getLeftTriggerAxis() {
return getRawAxis(Axis.kLeftTrigger.value);
}
private double getRawAxis(int value) {
return 0;
}
/**
* Get the right trigger (RT) axis value of the controller. Note that this axis is bound to the
* range of [0, 1] as opposed to the usual [-1, 1].
*
* #return The axis value.
*/
public double getRightTriggerAxis() {
return getRawAxis(Axis.kRightTrigger.value);
}
/**
* Read the value of the left bumper (LB) button on the controller.
*
* #return The state of the button.
*/
public boolean getLeftBumper() {
return getRawButton(Button.kLeftBumper.value);
}
/**
* Read the value of the right bumper (RB) button on the controller.
*
* #return The state of the button.
*/
public boolean getRightBumper() {
return getRawButton(Button.kRightBumper.value);
}
How can I check if the triggers were pushed, and then use that information in an if statement. So like, if LTrigger is pressed, print "being pushed" or something like that. Thanks so much!

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.

For each loop set value

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.

Is this MVC method a good way to program a Sudoku Game?

I'm building a Sudoku Game. I came here to get some help because I'm completely stuck in my code. I'm not asking for you to complete my code, I know that's not your job. Just few hints as what to do next would be great!
I use MVC and Swing Components for GUI to make the code lighter. I divided each field and method so I can understand what to do next but I'm confused. I'm particularly having trouble understanding how to do the following methods:
initializeGrid
chooseGameDifficulty
makeMove
cancelMove
Model
public class GameSudokuModel {
// states -- fields
Scanner userInput = new Scanner (System.in); // accept user input
// int levelDifficulty = 0; // level of difficulties
int [] gridSize ; // Sudoku 9x9 == 81 cells -- used to initialize grid or solve puzzle --
int [] subGridSize ; // a sub-grid = 9 cells
int gameMove = 0; // calculate the total number of moves per game // ++makeMove and --cancelMove
int [] gameCell = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // a cell contain a list of choices numbers 1-9
int currentGameTime = 0; // calculates the total time to complete a puzzle
String currentPlayerName = userInput.nextLine(); // player name
// end of fields
//behaviors -- methods
/******************************************************
*
* Method calculateGameTime (initialiserGrille)
*
*
* Calculates time
*
* The stopwatch starts when the player makes ​​his first move
*
*
*
******************************************************/
public class calculateGameTime{
}
/******************************************************
*
* Method initializeGrid (initialiserGrille)
*
*
* Used to initialize a grid
*
* Reset the grid ( back to the original Sudoku grid ) using the list of moves .
*
*
*
*
*
******************************************************/
public class initializeGrid {
}
/******************************************************
*
* Method levelDifficulty
*
*
* Established the parameters of level of difficulty
*
*
* #param beginner
* #param expert
* #return
******************************************************/
public int levelDifficulty (int beginner, int expert){
while(true)
{
int levelDifficulty = 0;
levelDifficulty= userInput.nextInt();
System.out.println (" ");
if(levelDifficulty < beginner || levelDifficulty> expert){
System.out.print (" You must choose 1, 2 or 3." + "Please try again : ");
System.out.println (" ");
}
else
return levelDifficulty;
}
}
/****************************************************
* Method chooseGameDifficulty (chosisirNiveauDifficulte)
*
* The method makes possible to choose the level of complexity of a grid
*
* (1) beginner: the player starts the game with a grid made ​​up to 75% (81 * 0.75)
*
* (2) Intermediate : the player starts the game with a grid made ​​up to 50% (81 * 0.50)
*
* (3) Expert : the player starts the game with a grid made ​​up to 25% (81 * 0.25)
*
* Numbers are set randomly on the grid every new game
*
* #param beginner
* #param intermediate
* #param expert
******************************************************/
public void chooseGameDifficulty(int beginner, int intermediate, int expert){
boolean entreeValide;
int levelDifficulty;
String reponse;
levelDifficulty= levelDifficulty(beginner,expert); // call function levelDifficulty()
if(levelDifficulty==beginner)
//get easy level grid (getter)
//set easy level grid (setter)
if(levelDifficulty==intermediate)
//get intermediate level grid (getter)
//set intermediate level grid (setter)
if(levelDifficulty==expert)
//get expert level grid (getter)
//set easy expert grid (setter)
}
/****************************************************
* Method solvePuzzle (resoudrePuzzle)
*
* This method makes possible to solve the entire grid meaning all the 81 cells
*
******************************************************/
public class solvePuzzle {
}
/****************************************************
* Method makeMove (fairePlacement)
*
* Save a record of the player's actions on the grid.
*
*
*
* (1) make move on the grid ;
* (2) save moves in an array list
*
******************************************************/
public class makeMove {
//choose a cell , enter a number on the cell and confirm the selection
// adds move to the array list
int makeMove = gameMove++;
}
/****************************************************
* Method cancelMove (annulerPlacement)
*
*
*
* (1) retrieve the last instance in the arraylist (using the remove method and the size method to determine the number of elements )
* (2) cancel the move in the grid.
*
******************************************************/
public class cancelMove {
//choose a cell , remove the number on the cell and confirm the cancellation
//substracts move from array list
int cancelMove = gameMove--;
}
}
initializeGrid and chooseGameDifficulty aren't really features of the model. The model maintains the current state of the data and the rules uses to manage it.
Technically, these features should be functions of some kind of factory that given a difficult level will return a instance of the model
public class SudokuFactory {
public enum Difficulty {
HARD,
MODERATE,
EASY
}
public SudokuModel createModel(Difficulty difficult) {
// Make a new model based on the rules for your difficulty
// settings
}
}
The model would then simply contain the information and functionality to manage it
You should also avoid static where practically possible, it should never be used as a cross class communication mechanism, if you need to share data, you should pass it. static just makes the whole thing a lot more difficult to manage and debug
The view would get the information from the user (like the difficulty level), which would be used by the controller to build a new model. The model would then be passed to a new controller, which would generate a new view, which should present the current state of the model.
The controller would then respond to changes in the view, updating the model and the controller would respond to changes in the model and update the view.
You should also prefer using interfaces over implementation
So, based on my (rather pathetic) understanding of Sudoku you could use a model as simple as ...
public interface SudokuModel {
public void setValueAt(int value, int row, int col) throws IllegalArgumentException;
public int getValueAt(int row, int col);
}
Now, me, personally, I'd have an implementation that had two buffers, one which represents the actual game/solution and one which represents the player data (pre-filled based on the difficulty level), now you could have a single buffer, but you'd have constantly scan the grid to see if the new value was valid and I'm just too lazy ;)

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