I need some help with designing the logic of my problem.
Model Bean
package com.ashish.model;
public class Model {
public Integer a,b,c,d;
public String f,g,h,i,j;
}
Service Class
package com.ashish.service;
import com.ashish.model.Model;
public class Service {
public StringBuilder query = null;
public Service(){
query = new StringBuilder("Select * from A where ");
}
public String build(Model m){
if(m.a != null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);
if(m.a == null&&m.b!=null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("b="+m.b);
if(m.a == null&&m.b==null&&m.c!=null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("c="+m.c);
if(m.a == null&&m.b==null&&m.c==null&&m.d!=null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("d="+m.d);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e!=null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("e="+m.e);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f!=null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("f="+m.f);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g!=null&&m.h==null&&m.i==null&&m.j==null)
query.append("g="+m.g);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h!=null&&m.i==null&&m.j==null)
query.append("h="+m.h);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i!=null&&m.j==null)
query.append("i="+m.i);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j!=null)
query.append("j="+m.j);
if(m.a != null&&m.b!=null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" b="+m.b);
if(m.a != null&&m.b==null&&m.c!=null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" c="+m.c);
if(m.a != null&&m.b==null&&m.c==null&&m.d!=null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" d="+m.d);
// ... 512 lines in this pattern
return query.toString();
return query.toString();
}
}
I want to write public String build(Model m) in such a way so that I would not have to write 512 if-else condition.
Conditions:
All instance variables of Model class can have two value ( null, not null)
They all can be null or they all can be not null.
There would be total 512 combinations ( since every instance variable have two state and there are 9 instance variable so total number of condition would be 2^9 )
Order of the instance variable does not matter.
My project use Java 6 so I can not use switch on String.
I have looked into various pattern but none of them is meeting my requirement.
Thanks for looking
A private helper method as follows should do it -
private void appendIfNotNull(String fieldOp, String val) {
if(val != null) {
query.append(fieldOp).append(val);
}
}
Then just call it in the build method -
public String build(Model m) {
appendIfNotNull("a=", m.a); //no null check, just need to repeat this for all fields
Maybe you want to try to use Java Reflection to read all fields of your Model and read them. You don't need to know the field name to read it. So it would be fully dynamic and generic, even if you extend your Model class.
Class modelClass = Class.forName(Model.class.getName());
Field[] fields = circleClass.getFields(); //includes all fields declared in you model class
for (Field f : fields) {
System.out.println("field " + f.getName() + " has value: " + f.get(<YOUR_MODEL_INSTANCE>));
}
Example code adapted from:
- http://forgetfulprogrammer.wordpress.com/2011/06/13/java-reflection-class-getfields-and-class-getdeclaredfields/
Will this code make sense?
interface ToStringer {
void appendTo(StringBuilder sb);
}
class NullToStringer implements ToStringer {
public void appendTo(StringBuilder sb) {
// Do nothing
}
}
class IntegerToStringer implements ToStringer {
private String fieldName;
private Integer val;
public IntegerToStringer(String fieldName, Integer val) {
this.fieldName = fieldName;
this.val = val;
}
public void appendTo(StringBuilder sb) {
sb.append(field).append(" = ").append(val);
}
}
public class ToStringFactory {
public ToStringer getToStringer(String fieldName, Integer val) {
if (val == null) {
return new NullToStringer();
} else {
return new IntegerToStringer(fieldName, val);
}
}
public ToStringer getToStringer(String fieldName, String val) {
...
}
}
public String build(Model m){
ArrayList<ToStringInstance> list = ...;
list.add(ToStringFactory.getToStringer("f", m.f));
list.add(ToStringFactory.getToStringer("g", m.g));
list.add(ToStringFactory.getToStringer("h", m.h));
StringBuilder sb = ...;
for (ToStringInstance tsi : list) {
tsi.appendTo(sb);
}
return sb.toString();
}
I am not sure what logic you are trying to implement, but the general approach: creating interface, concrete implementaion of printing values, using NullValue pattern to hide null problem and using factory to control objects creation should do the trick.
By using this approach you can avoid problems with 2^9 combinations by avoiding multiple if-else statements.
Update. Just came to my mind. You can use reflection. Iterate through all fields, get value of each, print it if it is no null. Maybe this will be enough.
It seems like you want to append to the query for each element that is not null. This can be done quite simply with an auxiliary method or two:
public class Service {
public StringBuilder query = null;
public Service(){
query = new StringBuilder("Select * from A where ");
}
public String build(Model m) {
boolean added = first;
first &= !maybeAdd("a", m.a, first);
first &= !maybeAdd("b", m.b, first);
. . . // all the rest of the fields of m
}
/**
* Add an equality test to an SQL query if the value is not {#code null}.
* #param key the field name for the query
* #param value the value to test for equality
* #param first flag indicating that no conditions have been added
* #return {#code true} if the value was appended; {#code false} otherwise.
*/
private boolean maybeAdd(String key, Object value, boolean first) {
if (value != null) {
if (!first) {
query.append(" AND ");
}
query.append(key).append('=').append(value);
return true;
}
return false;
}
}
Note that if all fields of the model are null, your query will not be correctly formed. You might want to include the appropriate logic in the maybeAdd method to compensate for that.
As I mentioned in my comment, you don't need a different if for every combination. You just need to append the values that are not null, and ignore the ones that are. Let me know if this works for you.
public String build(Model m) {
// use this to know when to add " AND " to separate existing values
boolean appended = false;
if (m.a != null) {
query.append("a=" + m.a);
appended = true;
}
if (m.b != null) {
if (appended) {
query.append(" AND ");
}
query.append("b=" + m.b);
appended = true;
}
if (m.c != null) {
if (appended) {
query.append(" AND ");
}
query.append("c=" + m.c);
appended = true;
}
if (m.d != null) {
if (appended) {
query.append(" AND ");
}
query.append("d=" + m.d);
appended = true;
}
if (m.e != null) {
if (appended) {
query.append(" AND ");
}
query.append("e=" + m.e);
appended = true;
}
if (m.f != null) {
if (appended) {
query.append(" AND ");
}
query.append("f=" + m.f);
appended = true;
}
if (m.g != null) {
if (appended) {
query.append(" AND ");
}
query.append("g=" + m.g);
appended = true;
}
if (m.h != null) {
if (appended) {
query.append(" AND ");
}
query.append("h=" + m.h);
appended = true;
}
if (m.i != null) {
if (appended) {
query.append(" AND ");
}
query.append("i=" + m.i);
appended = true;
}
if (m.j != null) {
if (appended) {
query.append(" AND ");
}
query.append("j=" + m.j);
appended = true;
}
return query.toString();
}
I don't know why you need two if statements for this:
if( m.a == null) {
query.append("m=null");
} else {
query.append("m="+m.a);
}
if( m.b == null) {
query.append("m=null");
} else {
query.append("m="+m.b);
}
Related
I've been staring at this forever, and neither my tutor nor classmates were able to find what might be happening. Any help at all would be so appreciated!
I have an error in my binary tree program somewhere that is causing for the lefthand leaf to be printed repeatedly and the righthand leaf to be skipped, but I can't figure out where it might be.
The assignment specifies the design and method signatures that we're to use, as well as using recursion in certain methods, so I can't change any of that. Each node has an array of up to two child nodes.
We need to format the printing so that each node is printed on the same line as its children.
For example:
Node rootNode = new Node("A");
rootNode.addChild("B", "A");
rootNode.addChild("E", "A");
rootNode.addChild("F","E");
rootNode.addChild("H","E");
rootNode.addChild("C", "B");
rootNode.addChild("D", "B");
rootNode.printTree();
Should return:
ABE
BCD
C
D
EFH
F
H
But is instead printing:
ABE
BCC
C
C
EFH
F
H
Node "D" is missing while "C" is getting reprinted, but somehow Node "H" (also the righthand leaf just like "D", but on the right branch instead of the left) is still getting printed correctly. When I use my find() method on "D" it returns null which seems to indicate it isn't getting put in the tree, so I think the error is in my addChild() method. I just can't for the life of me find where it is.
public boolean addChild(String ID, String parentID) {
if(myID.equals(parentID)) { // found parent
if(children[0] == null) {
children[0] = new Node(ID, find(parentID));
numberOfChildren++;
return true;
}
if (children[1] == null) {
children[1] = new Node(ID, find(parentID));
numberOfChildren++;
return true;
}
else {
// System.out.println("This is already full.");
return false;
}
}
else
{
if(numberOfChildren == 0) {
return false;
}
else if(numberOfChildren == 1) {
return children[0].addChild(ID, parentID);
}
else {
if(children[0].addChild(ID, parentID) == false) {
return children[1].addChild(ID, parentID);
}
else {
return children[0].addChild(ID, parentID);
}
}
}
}
Otherwise, the issue might be in the toString/print method:
public String toString() {
String childOne = "";
String childTwo = "";
if (children[0] != null) {
childOne = children[0].getId();
}
if(children[1] != null) {
childTwo = children[1].getId();
}
return(myID + childOne + childTwo);
}
#Override
public void printTree() {
// TODO Auto-generated method stub
System.out.println(toString() + " ");
if(children[0] != null) {
children[0].printTree();
}
if(children[1] != null) {
children[1].printTree();
}
}
}
Thank you in advance!!
package restaurantclient;
public class Restaurant extends Store {
//Instance Variables
private int peopleServed;
private double averagePrice;
//Constructor with 3 parameters
public Restaurant(String storename, int peopleServed, double averagePrice) {
super(storename);
setPeopleServed(peopleServed);
setAveragePrice(averagePrice);
}
//Getters (Accessors)
public int getPeopleServed() {
return peopleServed;
}
public double getAveragePrice() {
return averagePrice;
}
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
//toString Method [Must Override]
#Override
public String toString() {
String information = "Store name: " + (super.getName());
information += "\n" + "The number of people served: " + peopleServed;
information += "\n" + "The average price per person: $" + averagePrice;
return information;
}
//Equals Method
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!(this.getName().equals(otherRestaurant.getName())))
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed))
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
return true;
}
public double getAverageTaxes() {
double total;
total = this.getPeopleServed() * this.getAveragePrice()
* super.CA_TAX_RATE;
return total;
}
}
package restaurantclient;
public class Store {
//Instance Variables
protected final double CA_TAX_RATE = 0.0884;
private String storename;
//Constructor
public Store(String storename) {
setName(storename);
}
//Getters (Accessors)
public String getName() {
return storename;
}
//Setters (Mutators)
public void setName(String storename) {
this.storename = storename;
}
//toString Method [Must Override]
#Override
public String toString() {
String directory = "Name of store: " + storename;
return directory;
}
//Equals Method
public boolean equals (Store storename) {
if (this == storename)
return true;
if (storename == null)
return false;
if (!(storename instanceof Store))
return false;
return true;
}
}
Above are the equals methods I'm calling. They are displaying the wrong answers: it should be in the first instance, "They are not equal" and in the second instance after setting everything equal to each other, it should display, "They are equal". I have tried very hard on this problem and many things have not worked. There are no overt errors it runs fine, but I am doing something wrong and some precise guidance would be a lot of help. Much of the vague hints have got me nowhere. I need something concrete, if this makes to you. Thanks again for the help. The following is the Client class:
package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonald's", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
System.out.println();
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal."); //SHOULD say "not equal" here EVERY TIME the second instance (next comment down) says "Equal"...this should never change.
System.out.println();
}
System.out.println();
r2.setName(r1.getName());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal."); //Now that everything is equal, it should print "The Objects are Equal" but it doesn't. It's in lock-step with the previous instance. Changing some things like return true to return false might make both these instances "Are equal" and some might change them to "Not Equal" but they are never the way I want them, which is when 2 changes are made, they are not equal (first case) and when the third and final change is made (like this case here on this line) it should say "the obj are equal" but it doesn't.
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by the restaurant is: $");
System.out.println(r1.getAverageTaxes());
}
}
The reason that I see is simple, you are not getting the same name.
In equals, you are comparing super.getName() with otherRestaurant.getName()
If the superclass of Restaurant have a different format or return an other variable, since you compare it to Restaurant.getName(), this will compare different value. Using this.getName() to compare the same variable (or format of variable) is safer. Even if Restaurant.getName() is only returning the super.getName(), this would be safer if you changed the method of Restaurant (because you prefer it an other way).
Here is an example :
Restaurant:
public String getName(){
return "A restaurant " + name;
}
Super class :
public String getName(){
return name;
}
Will result into comparing "A restaurant : KFC" with "KFV".
Using the same getter assure you to return the same "format".
Aslo, your logic is wrong. You want to check if one of the value is different, if it is, return false. And if you reach the end of the method, meaning there where no difference leading to a return false, you return true.
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!super.getName().equals(otherRestaurant.getName())) // added ! here
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed)) // change to != here
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
//No differences, then it is equals.
return true;
Note :
This condition could be shorten
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
Since it is doing the same thing (comparing the values) :
if (averagePrice != (otherRestaurant.averagePrice))
return false;
Edit :
You are having a problem of overriding.
In Store:
public boolean equals(Store s){}
And in Restaurant
public boolean equals(Object o){}
Since you are calling the method with a Restaurant (subclass of Store), the JVM will use the Store.equals method since it match the type, Restaurant.equals is not overriding it, it override the method in Object. Change to Store.equals(Object o) to correct this.
The method equals comes from Object so it should be always receiving an Object to prevent any problem like this one, if you specify the type in a method, it will not override correctly the method (depending on the type)
Seems you are checking for equality and then returning false, when you should check for not equality to return false.
else if (!super.getName().equals(otherRestaurant.getName()))
return false;
else if (peopleServed != (otherRestaurant.peopleServed))
return false;
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
Also as asked, any reason to uses super.getName() ?
And since peopleServed & averagePrice cannot be null, the -1 check is not needed as the expected result we be the same as the equality check
And finally, I'm guessing the end return should be true, as it means it's different instance of an object, but they have all the same attributs.
Within your equals() method , If super.name() equals otherRestaurant.name() shouldn't you return true, here:
else if (super.getName().equals(otherRestaurant.getName())) return false;
Ok, that one will work in any cases:
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (name == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (name!=otherRestaurant.getName())
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != otherRestaurant.peopleServed)
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != otherRestaurant.averagePrice)
return false;
return true;
}
check it and reply if it is ok
private List<String> values = new ArrayList<String>();
public WhitespaceEqualsTest() {
values.add("I ");
values.add("I");
values.add(". ");
values.add(".");
values.add("1");
values.add("1 ");
System.out.println(refine(values));
}
private List<String> refine(List<String> input){
ArrayList<String> outerLoopValues = (ArrayList<String>) input;
ArrayList<String> innerLoopValues = (ArrayList<String>) input;
ArrayList<String> results = new ArrayList<String>();
for(String string1 : outerLoopValues){
for(String string2 : innerLoopValues){
if(string1.contains(string2) == false){
results.add(string1);
}
}
}
Set<String> temp = new HashSet<String>();
temp.addAll(results);
results.clear();
results.addAll(temp);
return results;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WhitespaceEqualsTest other = (WhitespaceEqualsTest) obj;
if (values == null) {
if (other.values != null)
return false;
} else if (!values.equals(other.values))
return false;
return true;
}
I've overriden the hashCode() and equals(), so I'm not really sure what's wrong. They are generated using Eclipse (Source -> Generate hashCode() and equals()). Why isn't it detecting that the same character without a space is contained within a character with a space? The output is:
[1, . , I , I, ., 1 ]
As mentioned in one of the comments, you should be using a String wrapper to wrap the strings and override the equals and hashcode methods.
My solution is based on the assumption that "I " should be equals to "I", hence only one of them should be added into the result.
However I'll need to addon that based on the documentation in Java Objects
and Java Arraylist with regards to equals and contains implementation respectively. The hashcode method would have to return a common value. I've written the explanation in the code as comments. Let me know if there are any issues.
Main Class
public class StackOverflowMain
{
private static List<String> values = new ArrayList<String>();
public static void main(String[] args) {
values.add("I ");
values.add("I");
values.add(". ");
values.add(".");
values.add("1");
values.add("1 ");
List<WhitespaceEqualsTest> toRefineList = new ArrayList<WhitespaceEqualsTest>();
for (String value : values) {
toRefineList.add(new WhitespaceEqualsTest(value));
}
System.out.println(refine(toRefineList));
}
private static List<WhitespaceEqualsTest> refine(List<WhitespaceEqualsTest> input) {
ArrayList<WhitespaceEqualsTest> loopValues = (ArrayList<WhitespaceEqualsTest>) input;
ArrayList<WhitespaceEqualsTest> results = new ArrayList<WhitespaceEqualsTest>();
for (WhitespaceEqualsTest value : loopValues) {
if (!results.contains(loopValues)) {
results.add(value);
}
}
Set<WhitespaceEqualsTest> temp = new HashSet<WhitespaceEqualsTest>();
temp.addAll(results);
results.clear();
results.addAll(temp);
return results;
}
}
Inner WhitespaceEqualsTest Class
class WhitespaceEqualsTest {
private String value;
public WhitespaceEqualsTest(String value) {
this.value = value;
}
public void setString(String value) {
this.value = value;
}
public String getString() {
return this.value;
}
public int hashCode() {
/*
* Arraylist.contains is evaluated by using (o==null ? e==null : o.equals(e)) as mentioned in the javadoc
* and Object.equals() would evaluate using hashcode() first to check if the object o is equal to object e
* before calling .equals() method to evaluate.
*
* As mentioned in java doc at http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#equals(java.lang.Object)
* c1.equals(c2) implies that c1.hashCode()==c2.hashCode() should be satisfied
* which is not in this question
*/
return 0;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WhitespaceEqualsTest other = (WhitespaceEqualsTest) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.contains(other.value) && !other.value.contains(value)){
/*
* Does a checking on both ends since "I " contains "I" but "I" does not contain "I " due to the whitespace
* For this question, if one of the condition satisfy it should be equal
*/
return false;
}
return true;
}
#Override
public String toString() {
return this.value;
}
}
Result
[I , . , 1]
String class is final. So you cannot override its equals and hashCode methods.
private List<StringWrapper> values = new ArrayList<StringWrapper>();
public WhitespaceEqualsTest() {
values.add(new StringWrapper("I "));
values.add(new StringWrapper("I"));
values.add(new StringWrapper(". "));
values.add(new StringWrapper("."));
values.add(new StringWrapper("1"));
values.add(new StringWrapper("1 "));
System.out.println(refine(values));
}
private List<StringWrapper> refine(List<StringWrapper> input){
//no need to iterate the list
//the set will automatically cancel out the duplicate
Set<StringWrapper> temp = new HashSet<StringWrapper>(input);
ArrayList<StringWrapper> results = new ArrayList<StringWrapper>();
results.addAll(temp);
return results;
}
Create a wrapper class of String then override the equals and hashcode method.
class StringWrapper {
private String value;
public StringWrapper(String value){
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString(){
return value;
}
#Override
public boolean equals(Object obj){
boolean result = Boolean.FALSE;
if(obj != null && obj instanceof StringWrapper){
StringWrapper stringWrapper = (StringWrapper) obj;
result = value.trim().equals(stringWrapper.getValue().trim());
}
return result;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value.trim() == null) ? 0 : value.trim().hashCode());
return result;
}
}
You add the values to a Set. In a Set in any case a value occurs once - hence it is a set. ;)
You might as well modify the loop to see what happens
for(String string1 : outerLoopValues){
for(String string2 : innerLoopValues){
if(string1.contains(string2) == false){
results.add(string1);
System.out.println("added \"" + string1 + "\" since it does not contain \"" + string2 + "\"");
}
}
}
Giving the following output:
added "I " since it does not contain ". "
added "I " since it does not contain "."
added "I " since it does not contain "1"
added "I " since it does not contain "1 "
added "I" since it does not contain "I "
added "I" since it does not contain ". "
added "I" since it does not contain "."
added "I" since it does not contain "1"
added "I" since it does not contain "1 "
......
[1, . , I , I, ., 1 ]
To add them if they do not contain each other is the idea i guess?
Then pushing the List through a Set removes the duplicates! See here: Does adding a duplicate value to a HashSet/HashMap replace the previous value
Changing the condition in the Loop from false to true yields this (no change after using the Set/HashSet in the last line of output!)
added "I " since it does contain "I "
added "I " since it does contain "I"
added "I" since it does contain "I"
added ". " since it does contain ". "
added ". " since it does contain "."
added "." since it does contain "."
added "1" since it does contain "1"
added "1 " since it does contain "1"
added "1 " since it does contain "1 "
[1, . , I , I, ., 1 ]
Which answers your question: It does detect if e.g. "I " contains "I".
System.out.println("I ".contains("I"));
says "true"
Hope this helps ^^-d
I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.
Is this the right way of validating using the instanceof keyword in java? Can I not use the || operator with this keyword? I am seeing errors in the line where I am writing the if condition to check if FieldName < = 0 and also when I am checking if it is equal to null or empty. Can anyone help me with the right way of writing the following piece of code. Thank you.
public static boolean validation(Object FieldName, String Name) {
if(FieldName instanceof Integer) {
if ((int) FieldName < = 0) {
errorCode = "EXCEPTION";
errorMsg = "Required field " + Name + " was not provided";
logger.debug(Name+ " is null ");
return true;
}
else {
}
}
else if (FieldName instanceof String) {
if(FieldName == null || FieldName.equals("")) {
errorCode = "EXCEPTION";
errorMsg = "Required field " +Name+" was not provided";
logger.debug(Name+" is null ");
return true;
}
//Here I check the fields for null or empty
}
Why not have two methods, one which takes an Integer and validates that, and one that validates Strings? Would that be simpler?
The line needs to be changed to
if (((int) FieldName) <= 0) {
when you don't put the parentheses around the cast completely the compiler will still believe it is an object and not an integer.
Try this. change the if and else body according to you
public static boolean validation(Object FieldName, String Name) {
if (FieldName instanceof Integer) {
if (((Integer)FieldName) <= 0) {
//an integer <= 0
return true;
} else {
// an integer >= 0
return true;
}
} else if (FieldName instanceof String) {
if (FieldName == null || FieldName.equals("")) {
// a String empty or null
return true;
}
else {
// a String non empty
return true;
}
}
return false;
}