Having trouble with some validating methods - java

I am having a bit of trouble on this homework on a couple things
First, they want me to create a method that checks whether the property type is one of the three types : mountain, fixie, cross-country. How do I go about doing this?
Second, they want me to create a method that fixes the string model if contains special characters. I created the method private boolean isValidModel(String model) to check that but am not sure if my fixing method is correct.
Lastly, how do I go about creating several instances of the bike class as mentioned below?
For reference the question is below.
Any help will be greatly appreciated
Write a class called Bike, which has three private properties: model, type, year - provide getters and setters for the properties. Don’t allow invalid data to be stored in the properties – year should be positive number, model should contain only letters, digits and spaces and type should be one of the following: mountain, fixie, cross-country. Provide private methods to validate the model and use it upon changing the model, also provide method to remove any invalid characters from the model so that you could save the new String into the model property.
private boolean isValidModel(String model)
private String fixModel(String model) // will return the model, with removed invalid characters
Also provide the public method display, which displays information about the bike:
public void display()
Write a main program to create several instances of the Bike class, try to set invalid data to the properties and invoke display after each change.
public class Bike
{
// Instance field
private String model;
private String type;
private int year;
public Bike(String model, String type, int year )
{
model = unknown;
type = unknown;
year = unknown;
}
//getters
public String getModel()
{
return model;
}
public String getType()
{
return type;
}
public int getYear()
{
return year;
}
//setters
public void setModel( String model )
{
model = N/A;
}
public void setType( String type )
{
type = N/A;
}
public void setYear( int year )
{
if(year < 1970)
year = 1970;
}
private boolean isValidModel(String model){
int len = model.length();
for (int i = 0; i < len; i++) {
if ((Character.isLetterOrDigit(model.charAt(i)) == false) && model.charAt(i)!=' ') {
return false;
}
}
return true;
}
private String fixModel(String model){
model= model.replaceAll("[^A-Za-z0-9]","");
}
public void display(){
System.out.println("Year: "+year+" Model: "+model+"Type: "+type);
}

You can check if the model is valid using different methods, I have did choose to use RegEx. If you still want to use your solution you have to change the '&&' (AND) symbol to an '||' (OR) symbol.
Bike class:
public class Bike {
private String model;
private String type;
private int year;
private boolean isValidModel(String model) {
// Making a pattern that checks for the requirements
Pattern pattern = Pattern.compile("[ A-Za-z0-9]*");
return pattern.matcher(model).matches();
}
private String fixModel(String model) {
// Replacing all the bad characters
return model.replaceAll("[^ A-Za-z0-9]", "");
}
public String getModel() {
return model;
}
public void setModel(String model) {
// Check if the Model is valid
if (this.isValidModel(model))
this.model = model; // If so store the model
else
this.model = this.fixModel(model); // Store the fixed model
}
public String getType() {
return type;
}
public void setType(String type) {
// Check if the type contains one of the hard coded types
if (type.equals("mountain") || type.equals("fixie") || type.equals("cross-country"))
this.type = type;
}
public int getYear() {
return year;
}
public void setYear(int year) {
if (year > 0) // Check if the year is positive
this.year = year;
}
public void display() {
// Displaying the stored information
System.out.println("Year:" + year + " Model:" + model + " Type:" + type);
}
}
The main method:
public static void main(String[] args) {
Bike bike1 = new Bike(); // Creating the first Bike instance
bike1.setModel("This Is Valid"); // Valid model
bike1.setYear(10); // Valid year
bike1.setType("cross-country"); // Valid type
Bike bike2 = new Bike(); // Creating the second Bike instance
bike2.setModel("This-Is-Invalid"); // Invalid model
bike2.setYear(-1); // Invalid year
bike2.setType("Invalid Type"); // Invalid type
bike1.display(); // Expected Year:10 Model:This Is Valid Type:cross-country
bike2.display(); // Expected Year:0 Model:ThisIsInvalid Type:null
}
I hope you find this answer helpful.

Related

Overriding add method for list to check if an attribute equals another instances attribute

!!!Only for practice!!!
Car is a immutable object which has attributes String owner, String registration....
So here is my code MyGarage implements Garage which contains a method add.
MyGarage also has a ArrayList which accepts a argument of type Car
The method is suppose to check if the car is all ready in the list by identifying the registration
Car
final class Car{
private String owner;
private final String registration;
private final String make;
private final int kilometres;
private final double price;
public Car(String ownerString, String registrationString, String makeString, int kilometresInt, double priceDouble){
owner = ownerString;
registration = registrationString;
make = makeString;
kilometres = kilometresInt;
price = priceDouble;
}
public String getOwner(){
return owner;
}
public String getRegistration(){
return registration;
}
public String getMake(){
return make;
}
public int getkilometres(){
return kilometres;
}
public double getprice(){
return price;
}
}
MyGarage
The method add is compareing if ti is not equal to null store it, how can I set this to if() the registration is already in the list do not add else add
import java.util.ArrayList;
public class MyGarage implements Garage {
private ArrayList<Car> myGarage;
public MyGarage() {
myGarage = new ArrayList<Car>();
}
#Override
public boolean add(Car c) {
for(Car car : myGarage) {
//This is where I make the ceck I am not sure how and I know this is only checking to make sure
//the value does not equal null not if it is the same registration
if(getCar(car.getRegistration())!=null) {
System.out.println("Car has the same Registration as another illegal");
return false;
}
}
myGarage.add(new Car(c.getOwner(),c.getRegistration(),c.getMake(),c.getkilometres(), c.getprice()));
return true;
}
}
Test Class
public class Test {
public static void main(String[] args) {
MyGarage garage = new MyGarage();
garage.add(new Car("Tom", "222","Honda", 1, 1000.99));
garage.add(new Car("Sam", "333","Honda", 2, 2000.99));
garage.add(new Car("Bob", "444","Ford", 3, 3000.99));
garage.add(new Car("Bob", "444","Ford", 3, 3000.99));
garage.display();
}
}
}
This will display all 4 Car objects in the list the 4th instance should not be allowed in the list

Compare objects by multiple fields in Java - dict method in Python

In python we can compare object by attributes by this method:
def __eq__(self, other):
return self.__dict__ == other.__dict__
It allows us to compare objects by their attributes no matter how many attributes they have.
Is something like this possible in Java?
I tried to compare objects in this way, but you have to compare them by every attribute. Is it possible to do it similarly to Python eq method above?
public class MyClass {
public MyClass(attr1, attr2, attr3, attr4) {
this.attr1 = attr1;
this.attr2 = attr2;
this.attr3 = attr3;
this.attr4 = attr4;
}
public boolean equals(Object object2) {
return object2 instanceof MyClass &&
attr1.equals(((MyClass)object2).attr1)&&......;
}
}
If you want to write general method that handles every type, you need to use reflection. If you just want to do this with a type or two, then I suggest you override the equals method for each individual type i.e. hardcoding it.
Here's how you write a generic method that accepts every single type and compares the fields for equality:
private static <T> boolean allFieldsEqual(T a, T b) throws IllegalAccessException {
Class<?> clazz = a.getClass();
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (!field.get(a).equals(field.get(b))) {
return false;
}
}
return true;
}
The logic is pretty self-explanatory. Here is the usage:
Student s1 = new Student("Tom", 1);
Student s2 = new Student("Tom", 1);
try {
System.out.println(allFieldsEqual(s1, s2));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Student is defined as:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}

What Pattern design to get rid of the type casting in my case?

public abstract class Employee {
String name;
String position
public Employee(String name, String position) {
this.name = name;
this.position = position
}
}
public class Pilot extends Employee {
public Pilot(String name,String position) {
super();
}
public void flight() {//flight the plane}
//getter and setter for the fields
}
public class Attendance extends Employee {
public Attendance(String name,String position) {
super();
}
public Food servingFood(String foodName) {}
}
// there will be many other positions
public class Company {
HashMap<String, ArrayList<Employee>> employeeTable; //values is a list of workers, key is the position
public Company() {this.employeeTable = new HashMap<>();}
public initializeEmployeeTable(file) {} //read file, and create keys in map (file contains information of the position)
public Worker hireEmployee(String position, String name){
if (position.equals("pilot")) {
Pilot p = Pilot(name);
employeeTable.get("pilot").add(p);
return p
}
else if (position.equals("flightAttendance")) {// the else if statement continuous to check the other position; }
}
public Worker callEmployee(String position, String name) {
for ( Employee e : employeeTable.get(position) ) {
if e.getName().equals(name) {
return e;
}
}
return null;
}
public static void main(String[] args) {
Company company = new Company();
company.initializeEmployeeTable(filePath);
File eventFile = new File(filePath); // event file describes what's happening in real world; read the lines, and call the program so that program simulates the real world events
sc = new Scanner(eventFile);
do {
String currentEvent = sc.nextLine();
String[] currentEventParts = currentEvent.split(", ");
if (currentEvent[0].equals("New Airplane")) { // currentEvent looks like {"New Airplane", "Attendance"// this part can be other position name, "Linda"}
Worker w = company.hireEmployee(currentEventParts[1], currentEventParts[2]); }
else if ((currentEvent[0].equals("flying"))) {
Worker w = company.callEmployee(currentEvent[0], currentEvent[1])
if (w.getPosition().equals("Pilot")) {(Worker) w.flight()}
if (w.getPosition().equals("Attendance")) {(Worker) w.serveFood()}
}
}
The reason there is HashMap for employee because there will be many positions; and reading the event file (when the first index is "New Airplane"); I don't want to go check the following index (would be name and position) with so many if statements to create corresponding employee. But when comes to calling specific methods, I need type casting now; since each method can be different (different type parameter, return type); so it's not ideal to have this methods be abstract method in super class employee and have the subclass implements the body.
Any advices: employee data structure; reading file strategy, pattern design would be appreciated. thanks

How can I make a class method work with another class method in an array?

For class I am suppose to make a program to simulate a police officer issuing a parking ticket to a car that is parked for too long. I am suppose to create four classes, ParkedCar, ParkingMeter, ParkingTicket, and PoliceOfficer. I'm just stuck on the main method because I have to make an array of two cars and make another array of two ParkingMeter, and make one car a violation, and the other a non-violation. How can I do this?
ParkedCar Class
// a class of type ParkedCar
public class ParkedCar {
// the class fields
private String make;
private String model;
private String color;
private String licenseNumber;
private int minutesParked;
// the class constructor
public ParkedCar(String mk, String mdel, String col, String lic, int minParked) {
// assign the constrictor fields to the class fields
make = mk;
model = mdel;
color = col;
licenseNumber = lic;
minutesParked = minParked;
}
// the copy constructor
public ParkedCar copy(ParkedCar car2) {
ParkedCar copyObject = new ParkedCar(make, model, color, licenseNumber, minutesParked);
return copyObject;
}
// getter method for make of a car
public String getMake() {
return make;
}
// setter method for make of a car
public void setMake(String make) {
this.make = make;
}
// getter method for model of a car
public String getModel() {
return model;
}
// setter method for model of a car
public void setModel(String model) {
this.model = model;
}
// getter method for color of a car
public String getColor() {
return color;
}
// setter method for a color of a car
public void setColor(String color) {
this.color = color;
}
// getter method for a car licence number
public String getLicenseNumber() {
return licenseNumber;
}
// setter method for a car licence number
public void setLicenseNumber(String licenseNumber) {
this.licenseNumber = licenseNumber;
}
// getter method for minutes parked
public int getMinutesParked() {
return minutesParked;
}
// setter method for minutes parked
public void setMinutesParked(int minutesParked) {
this.minutesParked = minutesParked;
}
}
ParkingMeter Class
// a class of type ParkingMeter
public class ParkingMeter {
// the class fields
private int minutesPurchased;
// the class constructor
public ParkingMeter(int numMinPurchased) {
// assign the constrictor fields to the class fields
this.minutesPurchased = numMinPurchased;
}
// getter method for minutes purchased
public int getMinutesPurchased() {
return minutesPurchased;
}
// setter method for minutes purchased
public void setMinutesPurchased(int minutesPurchased) {
this.minutesPurchased = minutesPurchased;
}
}
PoliceOfficer Class
// a class of type PoliceOfficer
public class PoliceOfficer {
// the class fields
private String name;
private String badgeNumber;
// the class constructor
public PoliceOfficer(String officeName, String badgeNumber) {
// assign the constrictor fields to the class fields
name = officeName;
this.badgeNumber = badgeNumber;
}
// the copy constructor
public PoliceOfficer copy(PoliceOfficer officer) {
PoliceOfficer copyObject = new PoliceOfficer(name, badgeNumber);
return copyObject;
}
// the method patrol looks at the number of minutes a car has been parked and the
// number of minutes purchased
public ParkingTicket patrol(ParkedCar car, ParkingMeter meter) {
ParkingTicket ticket = null;
// Calculate the total number of minutes parked over minutes
// purchased
int illegalMinutes = car.getMinutesParked()
- meter.getMinutesPurchased();
// if illegalMinutes, give ticket
if (illegalMinutes > 0) {
// yes, it is illegally parked.
ticket = new ParkingTicket(car, this, illegalMinutes);
}
return ticket;
}
// a getter method to get name of officer
public String getName() {
return name;
}
// a setter method to set name of officer
public void setName(String name) {
this.name = name;
}
// a getter method to get officer badge number
public String getBadgeNumber() {
return badgeNumber;
}
// a setter method to set officer badge number
public void setBadgeNumber(String badgeNumber) {
this.badgeNumber = badgeNumber;
}
}
ParkingTicket Class
// a class of type ParkingTicket
public class ParkingTicket {
// the class fields
private ParkedCar car;
private PoliceOfficer officer;
private double fine;
private int minutes;
public final double BASE_FINE = 25.0;
public final double HOURLY_FINE = 10.0;
// the class constructor
public ParkingTicket(ParkedCar aCar, PoliceOfficer anOfficer, int meterMins) {
// assign the constrictor fields to the class fields
car = aCar;
officer = anOfficer;
minutes = meterMins;
}
// a copy constructor
public ParkingTicket copy(ParkingTicket ticket) {
ParkingTicket copyObject = new ParkingTicket(car, officer, minutes);
return copyObject;
}
// The method calculateFine calculates the amount of a parking fine
public void calculateFine() {
double hours = minutes / 60.0;
int hoursAsInt = (int) hours;
if ((hours - hoursAsInt) > 0) {
hoursAsInt++;
}
// Assign the base fine.
fine = BASE_FINE;
// Add the additional hourly fines.
fine += (hoursAsInt * HOURLY_FINE);
}
// getter method to get a car
public ParkedCar getCar() {
return car;
}
// setter method to set a car
public void setCar(ParkedCar car) {
this.car = car;
}
// getter method to get officer
public PoliceOfficer getOfficer() {
return officer;
}
// setter method to set officer
public void setOfficer(PoliceOfficer officer) {
this.officer = officer;
}
// getter method to get fine
public double getFine() {
return fine;
}
// setter method to set fine
public void setFine(double fine) {
this.fine = fine;
}
// getter method to get minutes
public int getMinutes() {
return minutes;
}
// setter method to set minutes
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public String toString() {
return "ParkingTicket [car=" + car + ", officer=" + officer
+ ", fine=" + fine + ", minutes=" + minutes
+ ", BASE_FINE=" + BASE_FINE + ", HOURLY_FINE="
+ HOURLY_FINE + "]";
}
}
The Main Method
// a class of type PatrolSimulation
public class PatrolSimulation {
// the main method
public static void main(String[] args) {
// an array of 2 Car objects, with various minutesParked values
ParkedCar[] car = new ParkedCar[2];
car[0] = new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 100);
car[1] = new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 30);
// an array of 2 ParkingMeter objects, with minutes so that
// the first Car object is in violation, while the second is not
ParkingMeter[] meter = new ParkingMeter[2];
meter[0] = new ParkingMeter(30);
meter[1] = new ParkingMeter(40);
// an array of 2 ParkingTicket objects
ParkingTicket[] ticket = new ParkingTicket[2];
// a PoliceOfficer object
PoliceOfficer officer = new PoliceOfficer("Sargent Cody", "007");
}
}
The Main Method Pseudocode
// Create an array of 2 Car objects, with various minutesParked values
// Create an array of 2 ParkingMeter objects, with minutes so that
// the first Car object is in violation, while the second is not
// Create an array of 2 ParkingTicket objects
// Create a PoliceOfficer object. Give the officer a name and badge
// number
// Have the officer patrol each of the Car and ParkingMeter object
// combinations (index i for the array of Car objects should be
// matched with index i for the array of ParkingMeter objects, which
// should be matched with index i of the array of ParkingTicket
// objects)
// After the PoliceOfficer has patrolled the cars and parking
// meters, walk over the array of ParkingTickets and invoke the
// toString method if a ticket has been issued, otherwise indicate
// that a ticket has not been issued
The arrays you have look correct, but perhaps could be improved with inline initialization. You just need to it iterate over those arrays with a for loop:
public class PatrolSimulation {
public static void main(String[] args) {
ParkedCar[] cars = new ParkedCar[] {
new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 100),
new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 30)
};
ParkingMeter[] meters = new ParkingMeter[] {
new ParkingMeter(30),
new ParkingMeter(40)
};
ParkingTicket[] tickets = new ParkingTicket[cars.length];
PoliceOfficer officer = new PoliceOfficer("Sargent Cody", "007");
for (int i = 0; i < cars.length; i++) {
tickets[i] = officer.patrol(cars[i], meters[i]);
}
for (ParkingTicket ticket : tickets) {
if (ticket != null) {
ticket.calculateFine();
System.out.println(ticket.toString());
} else {
System.out.println("No ticket issued.");
}
}
}
}

how would I use an if statment to change the value of an attribute?

I want to be able to give a specific value to discount depending on certain requirements like the following age: > 25 and profession = teacher / professor get 10% discount, age < 25 and gradepoint > 7 get 25% discount
this is my code so far I am using double OO paradigm:
public class customer {
//attribute definitions
private String name;
private String address;
private String profession;
private Integer age;
private Integer gradepoint;
private double discount;
//constructor
public customer(String newName, String newAddress, String newProfession, Integer newAge, Integer newGradepoint, double newDiscount)
{
setName(newName);
setAddress(newAddress);
setProfession(newProfession);
setAge(newAge);
setGradepoint(newGradepoint);
setDiscount (newDiscount);
}
//getters
public String getName()
{ return name;}
public String getAddress()
{ return address;}
public String getProfession()
{ return profession;}
public Integer getAge()
{ return age;}
public Integer getGradepoint()
{ return gradepoint;}
public double getDiscount()
{ return discount;}
//setters
public void setName (String newName)
{ name = newName;}
public void setAddress (String newAddress)
{ address = newAddress;}
public void setProfession (String newProfession)
{ profession = newProfession;}
public void setAge (Integer newAge)
{ age = newAge;}
public void setGradepoint (Integer newGradepoint)
{ gradepoint = newGradepoint;}
public void setDiscount (double newDiscount)
{ discount = newDiscount;}
//methods
}
Would I need to create a sub class called discount or each type of discount? or I can write a method directly into this customer class to control the discount?
write a method directly into this customer class to control the discount?
This. Make it a calculated field. Kill setDiscount function, kill discount variable, and make the getDiscount function into something like:
public double getDiscount() {
if (...) return ...;
if (....) return ...;
...
}
...unless you want to have this as the default discount, and still allow modification, in which case keep discount as a property, and move this whole logic into the constructor, having conditional setDiscount() calls.
Your getDiscount function would ideally do the calculation and return the appropriate discount for the current object. For example:
public double getDiscount()
{
if (getAge() < 25 && getGradepoint() > 7)
{
return .25;
}
else if // other logic...
}
Although not the simplest solution, I would abstract the discount calculation to a separate interface and class as well as having an override discount value in the customer object.
E.g.
public interface DiscountManager<T>
{
public double getDiscount(T discountObject);
}
public abstract class AbstractCustomerDiscountManager extends DiscountManager<Customer>
{
public double getDiscount(Customer customer)
{
if (customer.hasCustomDiscount()) { return customer.getDiscount(); }
else { return calculateDiscount(customer); }
}
public abstract double calculateDiscount(Customer customer);
}
public class DefaultDiscountManager extends AbstractCustomerDiscountManager
{
public double calculateDiscount(Customer customer)
{
double discount = 0;
if ((customer.getAge() != null) && (customer.getAge() < 25)) { discount += 25; }
...
return discount;
}
}
Probably over time different rules evolve. At the spot where the discounting takes place, in the order, the discount and and a reference to the rule applied should be stored together.
This kind of business logic could have its own class. A generic solution would even be to store the rule as scriptable code (BeanShell = Java, or JavaScript) and use java's scripting API. So that this kind of business logic resides more with the business managers, and the rules can be presented and edited.

Categories