folks.... i have a child class GateNot which extends Gate. I'm not sure how to fill out the constructor of GateNot since Im not given any instance variables inside a child class. What would be the approach?
public class GateNot extends Gate {
public GateNot(Wire input, Wire output)
{
super()
}
}
import java.util.*;
public abstract class Gate implements Logic {
private List<Wire> inputs;
private Wire output;
private String name;
public Gate(String name, List<Wire> ins, Wire out)
{
this.name = name;
this.output = out;
if(ins.size() == 0 || ins.isEmpty())
throw new ExceptionLogicParameters(false, 1, 0);
else
this.inputs = ins;
}
#Override
public void feed(List<Signal> inSigs)
{
if(inSigs.size() != inputs.size())
throw new ExceptionLogicParameters(false, inputs.size(), inSigs.size());
else
{
for(int i = 0; i < inSigs.size(); i++)
{
inputs.get(i).setSignal(inSigs.get(i));
}
}
}
#Override
public void feed(String name)
{
if(!(this.name.equals(name)))
throw new ExceptionLogicMalformedSignal(name.charAt(0), "Invalid logic input");
else
{
Signal signalValue = Signal.fromString(name.charAt(0));
}
}
#Override
public List<Signal> read()
{
List<Signal> signals = new ArrayList<>();
signals.add(output.getSignal());
return signals;
}
#Override
public String toString()
{
return this.name+"( " + inputs.toString() + " | " + output.toString() + " )";
}
#Override
public boolean equals(Object other)
{
if(other instanceof Gate)
{
Gate someGate = (Gate)other;
return (this.inputs == someGate.inputs) && (this.output.equals(someGate.output)
&& (this.name.equals(someGate.name)));
}
else
return false;
}
public List<Wire>getInputs()
{
return this.inputs;
}
public Wire getOutput()
{
return this.output;
}
public String getName()
{
return this.name;
}
public void setInputs(List<Wire> inputs)
{
this.inputs = inputs;
}
public void setOutput(Wire output)
{
this.output = output;
}
public void setName(String name)
{
this.name = name;
}
}
You have to call the super class's constructor.
Based on the argument types and names of the super class's constructor, I'd say this is what you need :
public GateNot(Wire input, Wire output)
{
super("Not", Arrays.asList(new Wire[]{input}), output);
}
You can pass whatever String you wish as name
You should convert the input to a List of inputs
You can pass the output as is
Related
I having trouble figuring out how to print out how many times "Dr" titles appear in my array objects in my tester program as they contain more than one string. Is using the equals class the best way to approach this?
Note: I am using inheritance and polymorphism.
public class Driver {
public static void main(String[ ] args) {
Person[] persons = new Person[5];
persons[0] = new Person("John Smith");
persons[1] = new Person();
persons[2] = new TitledPerson("Rowan Bean", "Mr");
persons[3] = new TitledPerson("Phil McGraw", "Dr");
persons[4] = new TitledPerson("Hugo Strange", "Dr");
System.out.println("Person 3 and 4 are equal: " + persons[2].equals(persons[3]));
System.out.println();
String search = "Dr";
int counter = 0;
for(int i = 0; i < persons.length; i++) {
System.out.println(persons[i]);
if(persons[i] instanceof TitledPerson) {
if(persons[i].equals(search)) {
counter++;
}
}
}
System.out.println();
System.out.println("There are " + counter + " 'Dr' titles listed.");
}
}
Person Class:
public class Person {
private String name;
private final static String DEFAULT_NAME = "N/A";
public Person() {
this(DEFAULT_NAME);
}
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return "Name: " + name;
}
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person otherPerson = (Person) obj;
return name.equalsIgnoreCase(otherPerson.getName());
} else {
return false;
}
}
}
TitledPerson Class:
public class TitledPerson extends Person {
private String title;
public TitledPerson() {
}
public TitledPerson(String name, String title) {
super(name);
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
String parentString = super.toString();
parentString += ", " + title;
return parentString;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof TitledPerson) {
TitledPerson otherPers = (TitledPerson) obj;
return super.equals(obj) && this.title.equalsIgnoreCase(otherPers.title);
} else {
return false;
}
}
}
Change to using getTitle from your TitledPerson class while comparing with the search keyword.
if(((TitledPerson)persons[i]).getTitle().equals(search)) {
counter++;
}
The equals method in TitledPerson calls super class equals which will cause the name and title must be the same for equality.
I think the correct implementation of equals in TitledPerson should be
#Override
public boolean equals(Object obj) {
if(obj instanceof TitledPerson) {
TitledPerson otherPers = (TitledPerson) obj;
return this.title.equalsIgnoreCase(otherPers.title);
} else {
return false;
}
}
you seem to do this :
if(persons[i] instanceof TitledPerson) {
if(persons[i].equals(search)) {
counter++;
}
person is object with a name and a title
search on the other hand, is a string
so you need to do this :
if(persons[i] instanceof TitledPerson) {
if(persons[i].title.equals(search)) {
counter++;
}
this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}
I am wondering how can I define protected, public and private properties in my class GenericBean, which will result in a JavaBean. So far I've declared a class, that will enable use to access the value of the Bean, however, I have no idea how I can handle different accesses for those properties. Any idea? Here is m y class:
abstract class GenericBean {
protected PropertyChangeSupport chg = new PropertyChangeSupport(this);
protected VetoableChangeSupport veto = new VetoableChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener pcl) {
chg.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
chg.addPropertyChangeListener(pcl);
}
class BoundedProperty<T> implements PropertyChangeListener {
private String name;
private T value;
private Object chgHandlerObject;
private Method changeHandler;
public BoundedProperty(String name) {
this.name = name;
}
public T getValue() { return value; }
public void setValue(T newValue) {
T old = value;
value = newValue;
chg.firePropertyChange(name, old, value);
}
public void propertyChange(PropertyChangeEvent e) {
if (!e.getPropertyName().equals(name)) return;
if (changeHandler == null) return;
try {
changeHandler.invoke(chgHandlerObject);
} catch(Exception exc) {
exc.printStackTrace();
}
}
public void setChangeHandler(Object handl, String mname) {
try {
Method m = handl.getClass().getDeclaredMethod(mname);
chgHandlerObject = handl;
changeHandler = m;
chg.addPropertyChangeListener(this);
} catch(Exception exc) {
exc.printStackTrace();
return;
}
}
public void setChangeHandler(Object ohandler) {
try {
Method m = ohandler.getClass().getDeclaredMethod(name+"Change");
chgHandlerObject = ohandler;
changeHandler = m;
} catch(Exception exc) {
exc.printStackTrace();
return;
}
chg.addPropertyChangeListener(this);
}
public void removeChangeHandler() {
changeHandler = null;
chgHandlerObject = null;
chg.removePropertyChangeListener(this);
}
}
}
So that I can decide which methods are available for certain fields?
My goal is to modify my setters to throw tractorException if invalid values are passed in then modify my main method to try and catch the exceptions. The problem is I do not know how to modify my setters to make a exception error. Please Help.
import java.util.*;
public class tractorException
{
protected String name;
protected int VehicleID;
public String setName(String name)
{
return this.name = name;
}
String getName()
{
return this.name;
}
public int setVehicleID(int VehicleID)
{
if (VehicleID <= 0 || VehicleID > 100000)
{
return -1;
}
else
{
this.VehicleID = VehicleID;
return VehicleID;
}
}
public int getVehicleID()
{
return this.VehicleID;
}
tractorException()
{
setVehicleID(0);
setName("");
}
#Override
public String toString()
{
return "Tractor Name= " + name + "VIN= " + VehicleID;
}
public static void main (String[] args)
{
}
}
Try doing:
public class TractorException extends Exception
{
//implement whatever methods are necessary
}
In a class that represents a Tractor.
public int setVehicleID(int VehicleID) throws TractorException
{
if (VechicleID <= 0) {
throw new TractorException("Invalid VIN: " + VehicleID);
}
else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
In your main method, catch TractorException
I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);