Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a quick question
Suppose I were to create a data definition class named Campaign
and then I want to make an implementation class
Let's say in this implementation class I have a few variables(campaignName, campaignType, campaignGoal) and some methods (getCampName, getCampType, getCampGoal).
I want to create two different campaigns classes, and then compare their information at the end of the program with a print method.
Would this be a proper way of declaring information for the first campaign:
Campaign campaign1 = new Campaign();
which is in the main method, and then let's say I want to get the name of the first campaign, which is just hardcoded for now
public static String campaign1.getCampName(){
campaign1.setCampName("IT Student Scholarship Fund");
}
I just wanted to know how to do this. Thank you.
getCampName() should look something like:
public String getCampName() { return this.campaignName; }
a then simply
campaign1.getName();
You should stop the practice of putting all of your code in a main method. Instead, instantiate your Campaign instances and call methods on each one using a driver method in your primary class. In addition, you can override the equals() method to do the comparison (or implement Comparator).
public class CampaignTest{
public void runTest(){
Campaign c1 = new Campaign("First Campaign");
Campaign c2 = new Campaign("Second Campaign");
Campaign c11 = new Campaign("First Campaign");
System.out.println("c1==c2: " + c1.equals(c2));
System.out.println("c2==c11: " + c2.equals(c11));
System.out.println("c1==c11: " + c1.equals(c11));
}
public static void main(String... args){
CampaignTest test = new CampaignTest();
test.runTest();
}
private class Campaign{
private String name;
public Campaign(String n){
this.name = n;
}
public String getName(){
return name;
}
#Override
public boolean equals(Object other){
if(other instanceof Campaign && ((Campaign)other).getName().equals(name)){
return true;
}
return false;
}
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Currently I am looking at refactoring a class and having been studying up on design patterns, I'm curious which if any are applicable to this scenario. How the current class looks:
public WebDriver window(int index) {//stuff};
public WebDriver window(String nameOrId) {//stuff};
public WebDriver windowByTitle(String title) {//title specific stuff};
public WebDriver frame(int index) {//stuff};
public WebDriver frame(String nameOrId) {//stuff};
public WebDriver frameByTitle(String title) {//title specific stuff};
public WebDriver alert(int index) {//stuff};
public WebDriver alert(String nameOrId) {//stuff};
public WebDriver alertByTitle(String title) {//title specific stuff};
now lets say that every single one of these 9 methods, I want to add an optional secondary paramater, that is a Duration for example:
public WebDriver window(int index, Duration of) {//stuff}
but I need such functionality on every one of these methods and don't want to create 9 overloaded methods, reusing a lot of the core code. Each one of these methods creates a new Wait which calls a standard constructor to create it, assuming a default Duration, but I want to offer the ability to provide their own Duration as well.
What pattern is best to take care of such a problem? I plan to rewrite the class completely but I want to create a good solid design.
My Thoughts:
Strategy pattern (WindowSwitchStrategy, FrameSwitchingStrategy, AlertSwitchingStrategy)
Some sort of Builder that when we create just one method we can build up state to decide if the duration should be passed onto the new Wait(); constructor or not.
Pseudo of window(int index) {} :
try {
new Wait().until(windowIsReady());
} catch(TimeoutException ex) {
//ex stuff
}
would like an optional duration here, and if so we do this instead, but giving great reusability when we don't need an explicit duration specified by the caller:
new Wait(duration).until(windowIsReady());
Wait looks like this:
public Wait() {}
public Wait(Duration duration) {}
Thanks
I think the problem is already in the code and should be removed first. If you use an approach something like this:
public static class Select {
final Type type;
// Only one of these should be set.
int index;
String key;
private Select(Type type) {
this.type = type;
}
private Select setIndex(int index) {
this.index = index;
return this;
}
private Select setKey(String key) {
this.key = key;
return this;
}
public static Select by(Type type, int index) {
assert (type == Index);
return new Select(type).setIndex(index);
}
public static Select by(Type type, String key) {
assert (type != Index);
return new Select(type).setKey(key);
}
enum Type {
Index,
NameOrId,
Title;
}
}
// Now only one of each.
public WebDriver window(Select select) {
}
public WebDriver frame(Select select) {
}
public WebDriver alert(Select select) {
}
private void test() {
// Easy to use.
window(Select.by(Index, 1));
window(Select.by(NameOrId, "hello"));
}
You can now add very simply the new parameters as now you just have one method of each type and don't need to add more to add other parameters.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am trying to calculate the print cost base on different paper size, single side or double side. So here is the detail:
Also need to support for other paper sizes will be added in the future.
And according to my design, developer can just create a A5 class for example to support other paper size, and add other condition in the factory class.
Could someone review my code and help me on whether I have to use interface instead of abstract class?
Here is my code:
PageBase:
public abstract class PageBase {
abstract double GetCost(int total, int color, boolean isSingleSide);
abstract void CalculateUnitPrice(boolean isSingleSide);
}
A4Page Class:
public class A4Page extends PageBase {
public double blackAndWhitePrintUnitCost;
public double colorPrintUniCost;
#Override
public double GetCost(int total, int color, boolean isSingleSide) {
CalculateUnitPrice(isSingleSide);
return color* colorPrintUniCost + (total-color)* blackAndWhitePrintUnitCost;
}
#Override
public void CalculateUnitPrice(boolean isSingleSide) {
if (isSingleSide) {
this.blackAndWhitePrintUnitCost = 0.15;
this.colorPrintUniCost = 0.25;
}
else {
this.blackAndWhitePrintUnitCost = 0.10;
this.colorPrintUniCost = 0.20;
}
}
}
PageFactory:
public class PageFactory {
public PageBase GetPage(String pageType) {
switch (pageType.toUpperCase()) {
case "A4":
return new A4Page();
default:
return new A4Page();
}
}
}
Main:
public class Main {
public static void Main() {
//read
PageFactory pageFactory = new PageFactory();
PageBase page = pageFactory.GetPage("A4");
page.GetCost(0,0,false);
}
}
Decorator is way more elegant than Factory to your problem.
For Decorator, you will need some classes and interfaces:
Interfaces: Colored, Side and Page. All interfaces has a method cost() to be implemented.
Classes: SingleSide, DoubleSide, ColorPage, BlankAndWhitePage, A4
Usage:
Page page1 = new A4(new SingleSide(new ColorPage()))
Page page2 = new A4(new DoubleSide(new BlankAndWhitePage()))
page1.cost();
You need to add some value to each component, to be summed and give the expected value. Each object has a "cost".
Some internals:
class A4 implements Page {
//constructor
private Side side;
public BigDecimal cost() {
return this.valueA4 + side.cost();
}
}
class SingleSide implements Side {
//constructor
private Colored colored;
public BigDecimal cost() {
return this.valueSingleSided+ colored.cost();
}
}
Something in this line could give you some insights about the best object organization.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Can you explain me, how to solve this task as like pseudocode?
I try to write something but not sure about this
Create classes Employee and Manager with methods which return the general
working experience and payment for work done. Give your suggestion about
relations between classes(is-a, has-a, use-a, etc) Find solution for avoiding
of duplicate code. Write well commented code with examples of using these classes.
Wrire code for reading and writing collection of these objects from (into) file.
Find employee with maximal working experience.
Find employee with maximal payment.
Write code for handling the incorrect format of incoming file.
class Employee {
private String name;
private int experience;
private double payment;
// Getters and setters for the 3 attributes
public Employee(String name, int experience, double payment) {
this.name = name;
this.experience = experience;
this.payment = payment;
}
public class Manager extends Employee {
public Manager(String name, int experience, double payment) {
super(name, experience, payment);
}
Manager manager = new Manager("Sue", 23,3500);
Manager manager1 = new Manager("John", 22,3000);
Manager manager2 = new Manager("Q", 12, 3200);
public double maxPayment() {
double maxPayment = 0;
if(manager.getPayment() > manager1.getPayment() && manager.getPayment() > manager2.getPayment()) {
System.out.println(manager.getName());
}
else if(manager1.getPayment() > manager.getPayment() && manager1.getPayment() > manager2.getPayment()) {
System.out.println(manager1.getName());
}
else {
System.out.println(manager2.getName());
}
return maxPayment;
}
}
}
You have to set the methods maxPayment and maxExperience as static because they are not related to a particular instance, you'll need to create in your main method some employee/manager and give them to the method throught a list for ex:
public static double maxPayment(List<Employee> list) {
return list.stream().mapToDouble(Employee::getPayment).max().getAsDouble();
}
public static double maxExperience(List<Employee> list) {
return list.stream().mapToDouble(Employee::getExperience).max().getAsDouble();
}
public static void main(String[] args) {
Manager manager = new Manager("Sue", 23, 3500);
Manager manager1 = new Manager("John", 22, 3000);
Manager manager2 = new Manager("Q", 12, 3200);
Manager employee1 = new Manager("Fred", 2, 3000);
List<Employee> list = new ArrayList<>(Arrays.asList(manager, manager1, manager2,employee1));
System.out.println(Manager.maxPayment(list)); //3500.0
System.out.println(Manager.maxExperience(list)); //23.0
}
The way with for-loop would be :
public static double maxPayment(List<Employee> list) {
double maxPay = 0;
for (Employee e : list)
maxPay = Math.max(maxPay, e.getPayment());
return maxPay;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i'm new to Java and I'm trying to write a code that Scan for some Patients' names, also ask them to enter (y/n) if they are allergicToGluten, and then I print out a list of name of all the patients that are allergicToGluten. I just learnt Arrays but i'm still struggling in assigning many values ( name + y/n ) to an Array. I need your help.
Thank you very much :D
You need to create a class that represents your patient. And then you can have array of patients
public class Patient{
private String name;
private boolean allergicToGluten;
public Patient(String name, boolean allergicToGluten){
this.name = name;
this.allergicToGluten = allergicToGluten;
}
public boolean isAllergicToGluten(){
return allergicToGluten;
}
public String getName(){
return name;
}
}
----
Patient[] patients = new Patient[patientCount];
If you don't know patientCount then you need resizable-array.
ArrayList<Patient> patients = new ArrayList<Patient>();
// ... reading 'name' and 'isAllergic' from input
patients.add(new Patient(name, isAllergic));
And then you can print list of allergic patients
for(p : patients){
if (p.isAllergicToGluten())
System.out.println(p.getName());
}
There is no way to allocate more than one value to an array, but you can make an array of some class with multiple fields in it. For example,
public class Patient {
public String name;
public boolean isAllergic;
public Patient(String name, boolean isAllergic) {
this.name = name;
this.isAllergic = isAllergic;
}
}
public class Patient_Driver {
public static void main(String[] args) {
Patient[] patients = new Patient[] {
new Patient("Steve", true),
new Patient("Mary", false)
};
for (int i = 0; i < patients.length; i++) {
if (patients[i].isAllergic) {
System.out.println(patients[i].name);
}
}
}
}
Output:
Steve
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm tryin to develop a small text-based fighting game and I'm using eclipse to help me out. I have two classes a Hero and Villian.
Hero Code so far:
public class Hero
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Hero
*/
public Hero()
{
// initialise instance variables
Health = 100;
Punch = -30;
Kick = -25;
Special = -55;
}
Villian Code so far:
public class Villian
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Villian
*/
public Villian()
{
// initialise instance variables
Health = 100;
Punch = -25;
Kick = -30;
Special = -50;
}
I want to make it turn-based as well so that when the hero attacks, it's the villian's turn. But I'm having trouble trying to construct a suitable method for the attacks. Can someone please help me with this?
The best way to solve this problem is to use inheritance.
You want to have one class called Entity which holds everything all things need on the game field:
public abstract class Entity {
private int Health;
private int attackDmg;
public Entity(int health, int attackDamage) {
this.health = health;
this.attackDamage = attackDamage;
}
}
Then the two classes you currently have simply inherent everything from Entity:
public class Hero extends Entity {
public Hero() {
super(100, 30);
}
}
and Villian:
public class Villian extends Entity {
public Villian() {
super(100, 20);
}
}
Now you probably want to have some methods that makes the Entity take damage. Because everybody should be able to take damage it comes into the Entity class. Also you probably want to have an attack method, that tells you how much damage the entities does:
public abstract class Entity {
// [...]
public void takeDamage(int damage) {
health -= dmg;
}
public void attack() {
return attackDamage;
}
}
Now you can write in your controller class (that handles all of the turn based logic):
player.takeDamage(villian.attack()); (Given that playeris your Playerand villian your Villian).
Of course this only is a small example, you could also make a method that take a String as an argument, which represents the method of the attack (like "kick" or "punch") and then return different amounts depending on the attack type.
Further infos to inheritance:
http://www.tutorialspoint.com/java/java_inheritance.htm and http://beginnersbook.com/2013/05/java-inheritance-types/
You might also be interested in a game making tutorial:
http://www.gametutorial.net/
You might take a variable like flag and set its value to 1 when hero's turn and its value to 0 when villan's turn
if(flag==1)
{
villans turn;
flag=0;
}
else if(flag==0)
{
heros turn;
flag=1;
}
This works