I have created a custom FEST Condition to verify that my actual string either matches or is equal to an expected String
public class StringMatchesOrIsEqualTo extends Condition<String>{
private String expectedStringOrExpression;
public StringMatchesOrIsEqualTo(final String expectedStringorExpression){
this.expectedStringOrExpression = expectedStringorExpression;
}
#Override
public boolean matches(String value) {
return value.matches(expectedStringOrExpression) || value.equals(expectedStringOrExpression);
}
}
Whenever the conditon fails i want it to display a message that shows me what the original and expected String was
currently the display string is
actual value:<'Some String'> should satisfy condition:<StringMatchesOrIsEqualTo>
is there a way that this message also displays what the match is made against ?
I tried overriding the toString method in the class
#Override
public String toString() {
return "string matches or is equal to : " + expectedStringOrExpression;
}
but that does not seem to work.
You want to set the description, which can be done by calling the Condition(String) constructor:
public StringMatchesOrIsEqualTo(final String expectedStringorExpression){
super("A String that matches, or is equal to, '" + expectedStringorExpression "'");
this.expectedStringOrExpression = expectedStringorExpression;
}
Alternatively, you could override description():
#Override
public String description()
{
return "A String that matches, or is equal to, '" + expectedStringorExpression "'");
}
Related
Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.
currently I have a code like this
public class Department {
public static final String MESSAGE_DEPARTMENT_CONSTRAINTS =
"Department names should only contain alphanumeric characters and spaces, and it should not be blank\n"
+ "Department names should start with a name, followed by 'Management'";
public static final String DEPARTMENT_VALIDATION_REGEX = "[\\p{Alnum}][\\p{Alnum} ]*";
public final String fullDepartment;
public Department(String department) {
requireNonNull(department);
checkArgument(isValidDepartment(department), MESSAGE_DEPARTMENT_CONSTRAINTS);
fullDepartment = department;
}
/**
* Returns true if a given string is a valid department name.
*/
public static boolean isValidDepartment(String test) {
return (test.matches(DEPARTMENT_VALIDATION_REGEX) && (test.indexOf("Management") >= 0));
}
#Override
public String toString() {
return fullDepartment;
}
#Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Department // instanceof handles nulls
&& fullDepartment.equals(((Department) other).fullDepartment)); // state check
}
#Override
public int hashCode() {
return fullDepartment.hashCode();
}
}
I would like the code to only allow only valid departments name to be created
Example:
Junior Management
Senior Management
However, now I'm facing a problem where the word Management can be placed at anywhere and it's still considered valid
Example:
Management
Management Junior
How can I ensure that the word Management is a requirement at the back of a department name when I'm creating a department? Thanks.
Just change this function to this:
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX)
&& test.endsWith("Management")
&& !test.equals("Management");
}
If you think you will need more sophisticated checks you can also change your department validation regex to:
public static final String DEPARTMENT_VALIDATION_REGEX = "(\\p{Alnum}+ )+Management";
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX);
}
Note that this will still allow "Management Management" and also "M8n8g3m3nt Management" since you used \\p{Alnum}. If you only need alphabet characters
use \\p{Alpha}. If you want to catch the exception of "Management Management" you might want to do:
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX)
&& !test.equals("Management Management");
}
You should be able to do it all through the regex, but might get too complicated and unreadable for just one exception you can easily check with .equals().
Two ways to do it
a. Using startsWith() and endsWith() in StringUtils ,or just startsWith() and endsWith() that String provides
boolean endsWith = StringUtils.endsWith("Managemet") && !StringUtils.startsWith("Managemet");
b. Using regex .*?Management$,in this expression using .*? to include space and other special characters
String str ="Test Management";
String regex = ".*?Management$";
System.out.println(str.matches(regex));
I don't know why this is not working, what am I writing wrong?
public class Testmain {
/**
* #param args
*/
public static void main(String[] args) {
Wat n1=new This("john","man");
System.out.println(((This)n1).toString());
// TODO Auto-generated method stub
}
}
Why am I getting this as an output :
This#68e26d2e
What I should get as an output is this :
John man
And yes I know the class names are random. So I wrote toString() method in the class "This", but it's still not working. I have a field firstname in the superclass and field gender in the subclass, but now in the output I'm not getting the gender, only firstname.
You must override method
#Override
public String toString() {
return "Name: " + name + " \n Gender:" + gender;
}
name, gender it's you private members which you set in the constructor.
This#68e26d2e is just the hexadecimal representation of the memory address of your This class. Every object will have this by default. To have your own String representation, you must override the toString() method.
#Override
public String toString() {
return < your String here >;
}
override the toString() method in This
ex:
#Override
public String toString() {
return "whatever you want";
}
I use a method
public String introduce()
{
return super.introduce();
}
which returns the value from introduce() method of super class. And assume introduce() method returns
Hey! I'm Steve and I'm 26 years old
In the same class,I also have another method
public String getAlter() {
return alter;
}
Now alter contains the value:
Jobs
Now, the question is how do I return the value
Hey! I'm Steve and I'm 26 years old. I'm also known as Jobs!
from the overridden method, ie
public String introduce()
{
return super.introduce();
}
Just concatinate the strings returned by the two methods:
#Override
public String introduce() {
return super.introduce() + ". I'm also known as " + getAlter() + "!";
}
You have to override the method introduce:
1) call the super class method introduce() -> returns "Hey! I'm Steve and I'm 26 years old"
2) use method getAlter() inside the overridden method introduce()"
public String getAlter() {
return "Jobs";
}
#Override
public String introduce() {
String msg = super.introduce();
String name = this.getAlter();
msg = msg + ". I'm also known as " + name + "!";
return msg;
}
public static void main(String[] args) {
Jobs jobs = new Jobs();
String msg = jobs.introduce();
System.out.println(msg);
}
public String introduce()
{
return super.introduce()+" I'm also known as "+getAlter();
}
You can use the result of super.introduce() to build your final result.
#Override
public String introduce() {
return super.introduce() + ". I'm also known as " + getAlter() + "!";
}
Note the #Override annotation to make it clear that I am hiding the super implementation.
Don't immediately return your call to super:
public String introduce()
{
return super.introduce() + getAlter();
// for clarity, you are essentially performing these operations:
// String response = super.introduce();
// response = response + " I'm also known as ";
// response = response + getAlter();
// return response;
}
Simple way is to append them like:
#Override
public String introduce() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(super.introduce());
strBuilder.append(" I'm also known as");
strBuilder.append(getAlter());
return strBuilder.toString();
}
Hope this help!
Here is an example of what I am trying to ask
superclass Name.java
public class Name{
protected String first;
protected String last;
public Name(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
public String initials(){
String theInitials =
first.substring(0, 1) + ". " +
last.substring(0, 1) + ".";
return theInitials;
}
and then the subclass is ThreeNames.java
public class ThreeNames extends Name{
private String middle;
public ThreeNames(String aFirst, String aMiddle, String aLast){
super(aFirst, aLast);
this.middle = aMiddle;
}
public String initials(){
String theInitials =
super.first.substring(0, 1) + ". " +
middle.substring(0, 1) + ". " +
super.last.substring(0, 1) + ".";
return theInitials;
}
so if i create an Threename object with ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith") and then call System.out.println(example1.initials()); I will get B.S.S. I get that.
My question is is there a way to call the initials method that is in the Name class so that my output is just B.S.
no. once you've overridden a method then any invocation of that method from outside will be routed to your overridden method (except of course if its overridden again further down the inheritance chain).
you can only call the super method from inside your own overridden method like so:
public String someMethod() {
String superResult = super.someMethod();
// go on from here
}
but thats not what youre looking for here.
you could maybe turn your method into:
public List<String> getNameAbbreviations() {
//return a list with a single element
}
and then in the subclass do this:
public List<String> getNameAbbreviations() {
List fromSuper = super.getNameAbbreviations();
//add the 3 letter variant and return the list
}
There are many ways to do it. One way: don't override Names#initials() in ThreeNames.
Another way is to add a method to ThreeNames which delegates to Names#initials().
public class ThreeNames extends Name {
// snip...
public String basicInitials() {
return super.initials();
}
}
I would instead leave initials alone in the superclass and introduce a new method that will return the complete initials. So in your code I would simply rename the initials method in ThreeNames to something else. This way your initials method is the same across the implementations of Name