You are now going to write the various methods in WizardController that animate the wizards. In order to follow the motion of the wizards properly you will need to slow the animation down. To help you do this we have provided a class method delay() in the WizardController class.
WizardController.delay(100);
So the question is write a public class method jump() that returns nothing. It should make the wizard passed as argument jump up one cell position from its current cell then return to its original cell. I have tried the code below and it compiles but not 100% sure if its correct..
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
...also I need to create an instance of wizard and execute the jump() method passing it as argument to check this works as expected. This I am unsure how to do.
here is the full code:
public class WizardController
{
/**
* instance variables
*/
private Wizard wizard1;
private Wizard wizard2;
private int numOfRepeats;
private static final int MIN_NUM_REPEATS = 1;
private static final int MAX_NUM_REPEATS = 3;
public static final int LAST_CELL = 11;
/**
* Constructor for objects of class WizardController.
*/
public WizardController(Wizard aWizard1, Wizard aWizard2)
{
super();
this.wizard1 = aWizard1;
this.wizard2 = aWizard2;
this.numOfRepeats = 0;
}
/* instance methods */
/**
* Prompts the user for a number of action repeats
* in the range 1 to 3 inclusive, and returns this number.
*/
public int promptForNumOfRepeats()
{
int moves;
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
try
{
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
}
catch (NumberFormatException anException)
{
moves = 0;
}
return moves;
}
/**
* Returns true if the argument is in the range 1 to 3 (inclusive),
* otherwise false.
*/
public boolean isValidNumOfRepeats(int aNumber)
{
return ((aNumber >= WizardController.MIN_NUM_REPEATS)
&& (aNumber <= WizardController.MAX_NUM_REPEATS));
}
/**
* Repeatedly prompts the user for a number of repeats of the moves,
* until they enter a valid input representing a number in the range 1 to 3
* inclusive, and then returns this number.
*/
public int getNumOfRepeats()
{
int repeats = this.promptForNumOfRepeats();
while (!this.isValidNumOfRepeats(repeats))
{
OUDialog.alert("That is not a valid number of game repeats");
repeats = this.promptForNumOfRepeats();
}
return repeats;
}
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
public static void delay(int ms)
{
try{
Thread.sleep(ms);
}
catch(Exception e)
{
System.out.println("Problem in delay methods");
}
}
}
here is the Wizard class for any wxtra help:
public class Wizard
{
/* instance variables */
private Triangle persona;
private int startCellX;
private int startCellY;
private OUColour startColour;
public static final int CELL_SIZE_X = 20;
public static final int CELL_SIZE_Y = 30;
/**
* Constructor for objects of class Wizard
*/
public Wizard(OUColour aColour, int cellY)
{
super();
this.persona = new Triangle(30, 30, aColour);
this.persona.setXPos(0);
this.persona.setYPos(cellY * Wizard.CELL_SIZE_Y);
this.startCellX = 0;
this.startCellY = cellY;
this.startColour = aColour;
}
/* instance methods */
/**
* returns the persona of the Wizard - so that it can be displayed
* in the graphical display window
*/
public Triangle getPersona()
{
return this.persona;
}
/**
* Resets the receiver to its "home" X position of 0.
*/
public void homeX()
{
this.persona.setXPos(this.startCellX * Wizard.CELL_SIZE_X);
}
/**
* Resets the receiver to its "home" Y position of startCellY * CELL_SIZE.
*/
public void homeY()
{
this.persona.setYPos(this.startCellY * Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE.
*/
public void left()
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X);
}
/**
* Increments the X position of the receiver by CELL_SIZE.
*/
public void right()
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE.
*/
public void up()
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y);
}
/**
* Increments the Y position of the receiver by CELL_SIZE.
*/
public void down()
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void leftBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X * numCells);
}
/**
* Increments the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void rightBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X * numCells);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void upBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y * numCells);
}
/**
* Increments the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void downBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y * numCells);
}
/**
* returns the cellX the wizard is currently on
*/
public int getCellX()
{
return this.persona.getXPos()/ Wizard.CELL_SIZE_X;
}
/**
* returns the cellY the wizard is currently on
*/
public int getCellY()
{
return this.persona.getYPos()/ Wizard.CELL_SIZE_Y;
}
/**
* sets the cellY the wizard is on to the argument
*/
public void setCellY(int aCellNumber)
{
this.persona.setYPos(aCellNumber * Wizard.CELL_SIZE_Y);
}
/**
* Returns a string representation of the receiver.
*/
#Override
public String toString()
{
return "An instance of class " + this.getClass().getName()
+ " in cell X:" + this.getCellX() + ", Y:" + this.getCellY()
+ ", colour " + this.persona.getColour();
}
Related
I implemented a delegate pattern to hide away the linear algebra libraries I wanted to benchmark, according to this, see:
public interface Matrix<M> {
/**
* Cols or this matrix
*
* #return columns
*/
int rows();
/**
* Rows of this matrix
*
* #return rows
*/
int cols();
/**
* Matrix multiplication, should throw if cols and rows do not match.
* Contract is This X in, i.e. this_rows*this_cols X in_cols*in_rows
*
* #param otherMatrix right operand
* #return new matrix multiplied
*/
M multiply(M otherMatrix);
/**
* Multiply each element with this scalar
*
* #param scalar to multiply with
* #return scaled with scalar
*/
M multiply(double scalar);
/**
* Add in to this matrix
*
* #param in right operand
* #return this + in
*/
M add(M in);
/**
* Add in to all elements of this.
*
* #param in scalar operand
* #return this.map(e - > e + in)
*/
M add(double in);
/**
* Subtract in from all elements of this
*
* #param in scalar operand
* #return this.map(e - > e - in);
*/
M subtract(double in);
/**
* Substract in from this matrix
*
* #param in right operand
* #return this[i][j] -= in[i][j]
*/
M subtract(M in);
/**
* Divide all elements by in
*
* #param in scalar operand
* #return in.map(e - > e / in);
*/
M divide(double in);
/**
* Map this matrix to a double, useful for reduce or trace implementations
*
* #param mapping f: This -> double
* #return a double value
*/
double map(Function<M, Double> mapping);
/**
* Map each element with this function
*
* #param mapping f: Double -> Double each element
* #return this.map(e - > mapping ( e));
*/
M mapElements(Function<Double, Double> mapping);
/**
* Sum this matrix over all entries.
*
* #return sum of this
*/
double sum();
/**
* Max of this matrix over all entries.
*
* #return max of this
*/
double max();
/**
* Index along a column of max, should only be used for vectors.
*
* #return index of max
*/
int argMax();
/**
* Transpose this matrix.
*
* #return transpose.
*/
M transpose();
enum MatrixType {
VECTOR, SQUARE
}
}
with this class:
public class UJMPMatrix implements Matrix<UJMPMatrix> {
private org.ujmp.core.Matrix delegate;
public UJMPMatrix(UJMPMatrix in) { this.delegate = in.delegate; }
public UJMPMatrix(org.ujmp.core.Matrix in) { this.delegate = in; }
public int rows() {
return (int) this.delegate.getRowCount();
}
public int cols() {
return (int) this.delegate.getColumnCount();
}
#Override
public UJMPMatrix multiply(UJMPMatrix otherMatrix) {
return new UJMPMatrix(this.delegate.mtimes(otherMatrix.delegate));
}
#Override
public UJMPMatrix multiply(double scalar) {
return new UJMPMatrix(this.delegate.times(scalar));
}
#Override
public UJMPMatrix add(UJMPMatrix in) {
return new UJMPMatrix(this.delegate.plus(in.delegate));
}
#Override
public UJMPMatrix add(double in) {
return new UJMPMatrix(this.delegate.plus(in));
}
#Override
public UJMPMatrix subtract(double in) {
return new UJMPMatrix(this.delegate.minus(in));
}
#Override
public UJMPMatrix subtract(UJMPMatrix in) {
return new UJMPMatrix(this.delegate.minus(in.delegate));
}
#Override
public UJMPMatrix divide(double in) {
return new UJMPMatrix(this.delegate.divide(in));
}
#Override
public double map(Function<UJMPMatrix, Double> mapping) {
return mapping.apply(this);
}
#Override
public UJMPMatrix mapElements(Function<Double, Double> mapping) {
double[][] elements = this.delegate.toDoubleArray();
double[][] out = new double[elements.length][elements[0].length];
for (int i = 0; i < elements.length; i++) {
for (int j = 0; j < elements[0].length; i++) {
out[i][j] = mapping.apply(elements[i][j]);
}
}
return new UJMPMatrix(out, rows(), cols());
}
#Override
public double sum() {
return this.delegate.getValueSum();
}
#Override
public double max() {
return this.delegate.max(Calculation.Ret.NEW, 0).doubleValue();
}
#Override
public UJMPMatrix transpose() {
return new UJMPMatrix(this.delegate.transpose());
}
#Override
public int argMax() {
double[] array = this.delegate.toDoubleArray()[0];
int argMax = -1;
double best = Double.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > best) {
best = array[i];
argMax = i;
}
}
return argMax;
}
}
However, when I want to use this abstraction, Java tells me that I cannot use any of these methods, because of the wildcard I need (?) to use to declare these matrices:
private void feedForward(final Matrix<? extends Matrix<?>> starter, final List<Matrix<? extends Matrix<?>>> actives) {
Matrix<? extends Matrix<?>> toPredict = starter;
actives.add(toPredict);
for (int i = 0; i < this.totalLayers - 1; i++) {
final Matrix<? extends Matrix<?>> x = this.weights[i].multiply(toPredict).add(this.biases[i]);
// Weights and Biases are also Matrix<? extends Matrix<?>>[].
// error: cannot resolve method multiply(Matrix<capture ? extends Matrix<?>>)
toPredict = this.functions[i + 1].function(x);
actives.add(toPredict);
}
}
Note: In the constructor of the Neural Network I let the caller decide what type of Matrix they want by a simple enum { OJ_ALGO, UJMP }, and call the Factory I implemented to intialise those matrices. The fields of the neural network look like this:
// Weights and biases of the network
private volatile Matrix<? extends Matrix<?>>[] weights;
private volatile Matrix<? extends Matrix<?>>[] biases;
private volatile Matrix<? extends Matrix<?>>[] dW;
private volatile Matrix<? extends Matrix<?>>[] dB;
Question: How do I declare, initialise and utilise the Matrix abstraction I implemented in this neural network library?
Your feedForward method needs a generic type to signify that both arguments must be of the same type (note the <M> before void) :
private <M> void feedForward(final Matrix<M> starter, final List<M> actives) {
And likewise your neural network class should declare the type of matrices it is using (assuming you don't want to use different implementations at the same time):
public class NeuralNetwork<M> {
private volatile Matrix<M>[] weights;
private volatile Matrix<M>[] biases;
private volatile Matrix<M>[] dW;
private volatile Matrix<M>[] dB;
As a side note, I'm not sure why these are declared as volatile.
Your interface should look like this:
public interface Matrix<M> {
Matrix<M> multiply(Matrix<M> otherMatrix);
M delegate();
And your implementation:
public class UJMPMatrix implements Matrix<org.ujmp.core.Matrix> {
private org.ujmp.core.Matrix delegate;
#Override
public UJMPMatrix multiply(Matrix<org.ujmp.core.Matrix> otherMatrix) {
return new UJMPMatrix(this.delegate.mtimes(otherMatrix.delegate()));
}
#Override
public org.ujmp.core.Matrix delegate() {
return delegate();
}
This question already has answers here:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException
(2 answers)
Closed 5 years ago.
I was trying to figure out why my code is throwing a "java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: core.FlightOrder$FlightTicket" exception.
I have class declared as:
public class FlightOrder implements Serializable
that contains a private Set of FlightTickets.
And an inner class declared as:
public class FlightTicket
The solution i read about, was to make the inner class "FlightTicket" a static class, but im not sure thats what I'm supose to do to make my code work properly.
can someone help me figure out whats the right way to approach this problem?
public class FlightTicket
{
/**
* The passenger for this ticket
*/
private Customer passenger;
/**
* passenger's seat
*/
private int seat;
/**
* passenger's row
*/
private int row;
/**
* The passenger's class in the plane
*/
private E_ClassType classType;
/**
* Full constructor
* #param passenger
* #param seat
* #param row
* #param classType
*/
public FlightTicket(Customer passenger, int seat, int row , String classType)
{
this.passenger = passenger;
setSeat(seat);
setRow(row);
setClassType(classType);
}
/**
* Partial constructor
* #param seat
* #param row
*/
public FlightTicket(int seat, int row)
{
setSeat(seat);
setRow(row);
}
//-------------------------------Getters And Setters------------------------------
/**
* seat has to be positive number
* #param seat
*/
public void setSeat(int seat) {
if(seat>0)
this.seat = seat;
}
/**
* row has to be positive number
* #param row
*/
public void setRow(int row) {
if(row>0)
this.row = row;
}
/**
*
* #return classType
*/
public E_ClassType getClassType() {
return classType;
}
public int getSeat(){
return seat;
}
public int getRow(){
return row;
}
/**
* set the class type from the array classType located in Constants.
* if the classType not exists, the default value is Economy.
* #param classType
*/
public void setClassType(String classType) {
for(E_ClassType c : E_ClassType.values())
{
if(c.toString().equals(classType))
{
this.classType = E_ClassType.valueOf(classType);
return;
}
}
this.classType = E_ClassType.Tourists;
}
public FlightOrder getOuterType() {
return FlightOrder.this;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + row;
result = prime * result + seat;
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightTicket other = (FlightTicket) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (row != other.row)
return false;
if (seat != other.seat)
return false;
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "FlightTicket [passenger=" + passenger + ", seat=" + seat
+ ", row=" + row + ", flight number=" + getFlight().getFlightNumber() + "]";
}
}// ~ END OF Inner Class FlightTicket
Making inner class Serializable will work and this is exactly that you are supposed to do if you want to serialize it together with the outer class. The following code demonstrates:
public class Outer implements Serializable {
class Inner implements Serializable {
int value = 17;
}
Inner inner = new Inner();
public static void main(String[] args) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
Outer obj = new Outer();
obj.inner.value = 22;
oout.writeObject(obj);
Outer r = (Outer) new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray())).readObject();
System.out.println(r.inner.value);
}
}
The output is 22, the value that has been correctly serialized and deserialized from the inner class field.
You just need to implement Serializable interface by all the classes which will be serialized. I mean all classes of instance variables declared in your serializable class should also implement Serializable.
In your case FlightTicket and Customer need implement Serializable.
In my application I need pageableListView combine with propertyListView. I just wonder why pageableListView doesnt have contructor without model or list. I just create new class which extend propertyListView and have body with pageableListView and one additional constructor just with string = id and number of rows. Now it looking good and also it work. Did I miss something that this shouldnt work sometimes ?
package org.toursys.web.components;
import java.util.List;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.model.IModel;
public abstract class PropertyPageableListView<T> extends PropertyListView<T> implements IPageableItems {
private static final long serialVersionUID = 1L;
/** The page to show. */
private int currentPage;
/** Number of rows per page of the list view. */
private int itemsPerPage;
/**
* Constructor
*
* #param id
* See Component
* #param model
* See Component
* #param itemsPerPage
* Number of rows to show on a page
*/
public PropertyPageableListView(final String id, int itemsPerPage) {
super(id);
this.itemsPerPage = itemsPerPage;
}
/**
* Constructor
*
* #param id
* See Component
* #param model
* See Component
* #param itemsPerPage
* Number of rows to show on a page
*/
public PropertyPageableListView(final String id, final IModel<? extends List<? extends T>> model, int itemsPerPage) {
super(id, model);
this.itemsPerPage = itemsPerPage;
}
/**
* Creates a pageable list view having the given number of rows per page that uses the provided object as a simple
* model.
*
* #param id
* See Component
* #param list
* See Component
* #param itemsPerPage
* Number of rows to show on a page
* #see ListView#ListView(String, List)
*/
public PropertyPageableListView(final String id, final List<? extends T> list, final int itemsPerPage) {
super(id, list);
this.itemsPerPage = itemsPerPage;
}
/**
* Gets the index of the current page being displayed by this list view.
*
* #return Returns the currentPage.
*/
public final int getCurrentPage() {
// If first cell is out of range, bring page back into range
while ((currentPage > 0) && ((currentPage * itemsPerPage) >= getItemCount())) {
currentPage--;
}
return currentPage;
}
/**
* Gets the number of pages in this list view.
*
* #return The number of pages in this list view
*/
public final int getPageCount() {
return ((getItemCount() + itemsPerPage) - 1) / itemsPerPage;
}
/**
* Gets the maximum number of rows on each page.
*
* #return the maximum number of rows on each page.
*/
public final int getItemsPerPage() {
return itemsPerPage;
}
/**
* Sets the maximum number of rows on each page.
*
* #param itemsPerPage
* the maximum number of rows on each page.
*/
public final void setItemsPerPage(int itemsPerPage) {
if (itemsPerPage < 0) {
itemsPerPage = 0;
}
addStateChange();
this.itemsPerPage = itemsPerPage;
}
/**
* #return offset of first item
*/
public int getFirstItemOffset() {
return getCurrentPage() * getItemsPerPage();
}
/**
* #see org.apache.wicket.markup.html.navigation.paging.IPageableItems#getItemCount()
*/
public int getItemCount() {
return getList().size();
}
/**
* #see org.apache.wicket.markup.html.list.ListView#getViewSize()
*/
#Override
public int getViewSize() {
if (getDefaultModelObject() != null) {
super.setStartIndex(getFirstItemOffset());
super.setViewSize(getItemsPerPage());
}
return super.getViewSize();
}
/**
* Sets the current page that this list view should show.
*
* #param currentPage
* The currentPage to set.
*/
public final void setCurrentPage(int currentPage) {
if (currentPage < 0) {
currentPage = 0;
}
int pageCount = getPageCount();
if ((currentPage > 0) && (currentPage >= pageCount)) {
currentPage = pageCount - 1;
}
addStateChange();
this.currentPage = currentPage;
}
/**
* Prevent users from accidentally using it.
*
* #see org.apache.wicket.markup.html.list.ListView#setStartIndex(int)
* #throws UnsupportedOperationException
* always
*/
#Override
public ListView<T> setStartIndex(int startIndex) throws UnsupportedOperationException {
throw new UnsupportedOperationException("You must not use setStartIndex() with PageableListView");
}
/**
* Prevent users from accidentally using it.
*
* #param size
* the view size
* #return This
* #throws UnsupportedOperationException
* always
* #see org.apache.wicket.markup.html.list.ListView#setStartIndex(int)
*/
#Override
public ListView<T> setViewSize(int size) throws UnsupportedOperationException {
throw new UnsupportedOperationException("You must not use setViewSize() with PageableListView");
}
}
It would be easier for you to extend PageableListView and just add one method to make it work like PropertyListView:
/**
* Wraps a ListItemModel in a CompoundPropertyModel.
*
* #param model
* #param index
* #return a CompoundPropertyModel wrapping a ListItemModel
*/
#Override
protected IModel<T> getListItemModel(final IModel<? extends List<T>> model, final int index)
{
return new CompoundPropertyModel<T>(super.getListItemModel(model, index));
}
You can file a RFE for the additional constructor too.
I'm in my first semester of Java and I need help in calling methods from the VotingMachine class below to the Candidate Class. The Voting Machine class is compiling properly. Thank you all for any help you can provide....
Mercedes
import java.util.ArrayList;
/**
* These are the fields for the Voting Machine Class.
*/
public class VotingMachine
{
private ArrayList<String> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<String>();
}
/**
* This constructor will store the Candidates for the Candidate List
*/
public void setCandidateList()
{
candidateList.add("Darnell Woffard");
candidateList.add("Barack Obama");
candidateList.add("Hillary Clinton");
}
/**
* This method will display the entire Candidate List.
*/
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.println(candidateList.get(index));
}
}
/**
* Method to the number of Candidates in the CandidateList Arraylist.
*/
public int getNumberofFiles()
{
return candidateList.size();
}
/**
* Method to select one candidate by first providing an index number.
*/
public void listFile(int index)
{
if(index >= 0 && index < candidateList.size()){
String filename = candidateList.get(index);
System.out.println(filename);
}
}
/**
* This method will enable a user to remove a candidate.
*/
public void removeFile(int index)
{
if(index >= 0 && index < candidateList.size()){
candidateList.remove(index);
}
}
/**
* This method will add a file to the Candidate List.
*
*/
public void addCandidate(String filename)
{
candidateList.add(filename);
}
//----------
//The Candidate Class:
public class Candidate{
private String name;
private char party;
private String candidateList;
// Add fields
/**
* Fields
* name - Candidate's name, stored in a String
* party - Candidate's political party, stored in a char
* as 'r' for Republican, 'd' for Democrat, and 'i' for Independent
*/
/**
* Constructor
*
* #param anyName - caller inputs Candidate name
* #param anyParty - caller inputs Candidate's party affiliation
* stored as a char
* chars are assigned with single quotes.
*/
public Candidate(String anyName, char anyParty)
{
name = anyName;
party = anyParty;
}
/**
* The method will enable method calls from the Voting Machine Class.
*/
public void main(String candidateList)
{
VotingMachine votingMachine = new VotingMachine();
}
/**
* This method will define the candidates party affiliation.
* public char setParty()
*/
//Complete the three methods and their comments.
/**
* Method to retrieve the Candidate's name for the caller.
* public String getName(String anyName)
*
*/
/**
* Method to retrieve the Candidate's party for the caller.
*
* #return
*/
/**
* Method to change the Candidate's party
*
* #param
*/
Actually what i got from this is you are trying to make a voting machine. VotingMachine is the main class here having info of different candidates. so we will make object of candidate in votingMachine class. Note: when we are supposed to make a java project, figure out what is it main class and subclass that means which depends on which. in the above example There is association in the classes. First of all declare an ArrayList for storing objects of candidate class. as shown below.
private ArrayList<candidate> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<String>();
}
now for adding new candidate in the ArrayList I have modified your method
setCandidate()
as
public void addNewCandidate(String name, char partySymbol)
{
candidate candid = new candidate(name, partySymbol);// this will call the candidate constructor
candidateList.add(candid);//add that object in ArrayList
}
As ArrayList stores references of objects, the built-in function int get(int index) will return the reference of the object. to print the info of that object or you can say values, we should define a function as getName() and getParty(). instead of this System.out.println(candidateList.get(index)); you should call System.out.println(candidateList.get(index).getName()); and System.out.println(candidateList.get(index).getParty());in the following method
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.println(candidateList.get(index));
}
}
so define functions in candidate class as
public String getName()
{
return name;
}
/**
* Method to retrieve the Candidate's party for the caller.
*
* #return
*/
public char getParty()
{
return party;
}
the following method will print the reference not the info of candidate, so modify it as described above
public void listFile(int index)
{
if(index >= 0 && index < candidateList.size()){
String filename = candidateList.get(index);
System.out.println(filename);
}
}
as i have modified it,
import java.util.ArrayList;
/**
* These are the fields for the Voting Machine Class.
*/
public class VotingMachine
{
private ArrayList<Candidate> candidateList;
/**
* The following constructor will establish the Candidate List
*/
public VotingMachine()
{
candidateList = new ArrayList<>();
}
/**
* This method will store the Candidates for the Candidate List
*/
public void addNewCandidate(String name, char partySymbol)
{
Candidate candid = new Candidate(name, partySymbol);// this will call the candidate constructor
candidateList.add(candid);//add that object in ArrayList
}
/**
* This method will display the entire Candidate List.
*/
public void printCandidateInfo()
{
for (int index=0; index < candidateList.size(); index++)
{
System.out.print(candidateList.get(index).getName());
System.out.println(" " + candidateList.get(index).getParty());
}
}
/**
* Method to the number of Candidates in the CandidateList Arraylist.
*/
public int getNumberofFiles()
{
return candidateList.size();
}
/**
* Method to select one candidate by first providing an index number.
*/
public void listFile(int index)
{
System.out.print(candidateList.get(index).getName());
System.out.println(" " + candidateList.get(index).getParty());
}
/**
* This method will enable a user to remove a candidate.
*/
public void removeFile(int index)
{
if(index >= 0 && index < candidateList.size()){
candidateList.remove(index);
}
}
}
in candidate class i have just added the above mentioned getName() and getParty() methods..
regards
Can anyone assist me to implement a component-based project? I have designed two components i.e calculator and engine (source codes below) which need to be inside any of the swing components (either JList , JTree, or any). Then there should be an ability of dragging any of the two components (calculator or engine) unto the editor pane for composition using a connector (code give below). If the composition is right, let the composite return unto the palette where the initial components were dragged from.
Components:
public class Engine {
private String name = "";
private boolean running = false;
private int speed;
public Engine(String name) {
this.name = name;
}
public void start() {
if (!running) {
running = true;
System.out.println("Engine starts.");
}
else
System.out.println("Engine already starts.");
}
public void stop() {
if (running) {
running = false;
speed = 0;
System.out.println("Engine stops.");
}
else
System.out.println("Engine already stops.");
}
public void setSpeed(int speed) {
if (speed >=0)
this.speed = speed;
}
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public class Calc {
public Calc() {
}
public Double squareRoot(Double a_double){
return Math.sqrt(a_double);
}
// pre an_int >= 0
public synchronized Integer factorial(Integer an_int){
int fact=1;
for(int i=1;i<=an_int;i++){
fact *= i;
}
return fact;
}
/**
*
* #param an_int
* #return the squared root of the input integer
*/
public Integer getSquareRoot(Integer an_int){
return (int) Math.sqrt(an_int);
}
public Double getSquareRoot(Double aDouble){
return Math.sqrt(aDouble);
}
/**
* Converts an Integer object into a Double object.
*
* #param an_int The Integer to be converted.
* #return The Double object representing the same value.
*
*/
public Double integerToDouble(Integer an_int){
return new Double(an_int.intValue());
}
/**
* Converts a Double object into an Integer object. Decimal digits are
* truncated. Useful when passing the output of a method as the input to another.
*
* #param a_double The Double to be converted.
* #return The Integer object representing the same value.
*
*/
public Integer doubleToInteger(Double a_double){
return new Integer(a_double.intValue());
}
public Integer sum(Integer a, Integer b) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a+b;
}
/**
* Returns a string representation of the calculator.
*/
public String toString(){
return("Calculator computation unit:\n"+super.toString());
}
void doNothing(){
}}
/////////////////////////////////////////////////////////////////////////////////////////
Your best bet is probably to leverage an existing GUI editor, where the one in Netbeans is rumoured to be good.
You will then need to add your components to the component palette. Check the Netbeans online help for further information.
Start with NetBeans, take a look at this answer, i give full details of how to create a component in NetBeans.