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.
Related
i created setter in sailor class and i want to change email in main class but why my setter wont change the email when its called?
i have tried to change the setter content and implement things to crew class toString method but i cant get it to work, any ideas?
import java.util.ArrayList;
class Sailor {
private String name;
private String email;
public Sailor(String name, String email) {
this.email = email;
this.name = name;
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
class Crew {
ArrayList<Sailor> sailorList = new ArrayList<>();
public Crew() {}
public void addCrewMember(Sailor sailor) {
sailorList.add(new Sailor(sailor.getName(), sailor.getEmail()));
}
public String toString() {
String content = "";
for (int i = 0; i < sailorList.size(); i++) {
content += sailorList.get(i).getName() + " (";
content += sailorList.get(i).getEmail() + ") \n";
}
return content;
}
}
class ObjectsCrewProgram {
public static void main(String[] args) {
Sailor firstSailor = new Sailor("Frank", "frank#mail.com");
Sailor secondSailor = new Sailor("Susan", "susan#mail.com");
Sailor thirdSailor = new Sailor("John", "john#sailors.com");
Sailor fourthSailor = new Sailor("Ann", "ann#sailors.com");
Crew firstCrew = new Crew();
Crew secondCrew = new Crew();
firstCrew.addCrewMember(firstSailor);
firstCrew.addCrewMember(secondSailor);
firstCrew.addCrewMember(fourthSailor);
secondCrew.addCrewMember(thirdSailor);
secondCrew.addCrewMember(secondSailor);
System.out.println("=== First crew ===\n" + firstCrew);
System.out.println("=== Second crew ===\n" + secondCrew);
secondSailor.setEmail("Susan#sailors.com");
System.out.println("===Second crew ===\n" + secondCrew);
}
}
why my setter wont change the email when its called?
It does. You're just never observing that change because your program never outputs that value.
You're outputting your crew values:
System.out.println("===Second crew ===\n" + secondCrew);
This uses your .toString() method to generate that output. But what does a "crew" object contain? It doesn't contain the "sailor" objects you provided to it. It contains copies of them:
public void addCrewMember(Sailor sailor) {
sailorList.add(new Sailor(sailor.getName(), sailor.getEmail()));
}
So your order of operations is:
Create a Sailor object.
Create a Crew object.
Add a copy of the Sailor to the Crew.
Modify the original Sailor.
Print the Crew.
Instead of creating a copy, just add the Sailor itself to the Crew:
public void addCrewMember(Sailor sailor) {
sailorList.add(sailor);
}
Then any changes you make to those Sailor objects will be visible in that Crew.
You are creating new sailors with this call:
public void addCrewMember(Sailor sailor) {
sailorList.add(new Sailor(sailor.getName(), sailor.getEmail()));
}
So you are copying the data and not adding the original sailor. So changing the original sailor has no effect.
How to pass multiple values to a single parameter for a particular method in java.
e.g. suppose i have a method with single parameter 'childname', that gets names of all the children in a family.
Now how can i pass multiple values to this parameter to get all different names.
public String getChildrenNames(String childname)
{
children= childname+ familyName;
return children;
}
You would typically implement this using either an Array, or a Collection.
eg:
public String[] getNamesOfChildren()
or
public Collection<String> getNamesOfChildren()
As people say you need to pass them as an Array, so your code should be like this:
String familyName = "Family";
public String[] getChildrenNames(String[] childnames)
{
String[] result = new String[childnames.length];
for(int i=0; i<childnames.length; i++)
{
result[i] = childnames[i] + " " +familyName;
}
return result;
}
public void main()
{
String[] childnames = {"Name1", "Name2", "Name3"};
String[] childnamesAux = getChildrenNames(childnames);
}
With this your childnamesAux variable should have: {"Name1 Family", "Name2 Family", "Name3 Family"}
If you can't change the signature of your method, then you can use concatenation, then in your method you can split this parameter for example :
String childname = firstname + "," + lastname;
getChildrenNames(childname);
so you can split this parametter to get multiple names,
String[] spl = childname.split(",");
But there are better ways then this, if you can change the signature of your method, so you can create a method which can take an array or list of names instead :
public String getChildrenNames(String...childnames) {
or
public String getChildrenNames(Lis<String> childnames) {
You can even create an Object for example :
class Person{
private String firstname;
private String lastname;
//getters and setters
}
Then your method should take an array or a list of Person Object :
public String getChildrenNames(List<Person> childname) {
You can try this
public static String child(String... name){
String[] array=name;
String tem;
if(name.length==1)
return name[0];
for(int counter=0; counter<array.length;counter+=2){
array[0]=name[counter]+name[counter+1];
}
tem=array[0];
return tem;
}
now if you call it
child("Paul","walker");
the output will be
Paul Walker
hope this helped
you can use var args like below
public String getChildrenNames(String... childname)
{
for(String s:childname)
{
children= childname+ s;
}
return children;
}
example
public class Test {
public static void main(String[] args) {
System.out.println(tes("s","d","s"));
}
static String tes(String... x)
{
String y="";
for(String s:x)
{
y=y+s;
}
return y;
}
}
output: sds
So I have this class "Member" :
package pkgData;
import java.io.Serializable;
public class Member implements Comparable<Member>, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String city;
public Member(String nameOfMember,String location) {
super();
this.name = nameOfMember;
this.city=location;
}
public String getNameOfMember() {
return name;
}
public String getLocationOfMember() {
return city;
}
public void setNameOfMember(String nameOfMember) {
this.name = nameOfMember;
}
#Override
public String toString() {
return name +", " + city;
}
#Override
public int compareTo(Member o) {
int result =this.getNameOfMember().compareTo(o.getNameOfMember());
if(result==0){
result = this.getLocationOfMember().compareTo(o.getLocationOfMember());
}
return result;
}
}
And I have a JComboBox which is EDITABLE and the model of the ComboBox is DefaultComboBoxModel.
So the problem is that if I cast the selectedItem:
Member nameOfMember = (Member)memberModel.getSelectedItem();
if(nameOfMember== null)
throw new Exception("please select a name and a location");
It only checks if the entered string is empty. If I enter a string like "Name, Location" I always get the exception that String cannot be cast to Member. Which String to I have to enter that the String can be cast to Member?
Here is my JComboBox:
private JComboBox<Member> getComboBoxMember() {
if (comboBoxMember == null) {
comboBoxMember = new JComboBox<Member>();
comboBoxMember.setEditable(true);
comboBoxMember.setModel(memberModel);
}
return comboBoxMember;
}
and here the global variables:
private DefaultComboBoxModel<Member> memberModel;
private JComboBox<Member> comboBoxMember;
String nameOfMember = (String) memberModel
.getSelectedItem();if(nameOfMember==null)throw new Exception("please select a name and a location");else
{
String[] parts = nameOfMember.split(",");
String part1 = parts[0]; // name
String part2 = parts[1]; // location
Member member=new Member(part1, part2);
}
String split & cast method
What you can do is first of all test if the string you get is null, or if it matches well you format. Then, you can create a new object with these elements.
Here's a small example code :
String memberData = (String)memberModel.getSelectedItem();
if(memberData == null || memberData.split(", ")[0].isEmpty() || memberData.split(", ")[1].isEmpty()) {
throw new Exception("Data is incorrect, please provide name and location separated with ", ");
}
Member member = new Member(memberData.split(", ")[0], memberData.split(", ")[1]);
JComboBox method
With Java 7 happened a new possibility of extension to JComboBox, which can now be generically parameterized (as for ArrayLists) in the form JComboBox<Type>. Thus, the objects you can get with getSelectedItem() can now be casted to the generic type you gave in parameter to JComboBox. The only problem is that, when a JComboBox is edited, as in your case, the data is casted to a simple String.
What you can do in your listener method (I will use ActionListener) is the following :
class ItemAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try {
//In case the user has not modified the object
Member member = (Member)box.getSelectedItem();
//Just an example here
if(member != null) {
System.out.println(member.toString());
}
} catch(ClassCastException ex) {
//In case the object has been modified
String data = (String)box.getSelectedItem();
//Apply first method here
}
}
}
But the problem with this method is that you end up using the first method still.
i want to split the mProductType is one list and mRetailerid is another list.how can i get it ????
public class RetailerNames implements Serializable{
private String mProductType;
private String mRetailerid;
public String getmProductType() {
return mProductType;
}
public void setmProductType(String mProductType) {
this.mProductType = mProductType;
}
public String getmRetailerid() {
return mRetailerid;
}
public void setmRetailerid(String mRetailerid) {
this.mRetailerid = mRetailerid;
}
#Override
public String toString() {
return mProductType + "," +
mRetailerid ;
}
I have used below code :
ArrayList<RetailerNames> retailerNamesList = (ArrayList<RetailerNames>) getIntent().getExtras().getSerializable("ProductsDetailsDescriptionPage");
System.out.println("The retailer details are"+" "+retailerNamesList);
Now my current output is:
The retailer details are [Krish,48, Danesh,47]
But i want to get the one list like [Krish,Danesh] .and [48,47] is separate another list.How can i do ???
please give me solution ???
please give me a ideas to split the array list to separate list???
ArrayList list = new ArrayList();
Iterator<RetailerNames > retaileriterator = retailerNamesList.iterator();
while(retaileriterator.hasNext()){
id=retaileriterator .next().getmRetailerid();
System.out.println(id);
list.add(id);
}
System.out.println(list);
In my condition getLocationDetails return arraylist
and LocationDetails is POJO same like your class RetailerNames
Iterator<LocationDetails> it= getUserLocationsWrapper.getLocationDetails().iterator();
while(locationCitiDetailsItr.hasNext()){
locationCitiDetailsItr.next().getCity());
}
same i think try this one
Iterator<RetailerNames > retaileriterator = retailerNamesList.iterator();
while(retaileriterator.hasNext()){
Object id=retaileriterator .next().getmRetailerid();
//add this id into another list
//same RetailerNames
}
use nested array
Put [Krish,48] is one list and
[damesh,47] in another list and put both the list in one main array list
Use like this
public class RetailerNames implements Serializable{
private String mProductType;
private String mRetailerid;
public String getmProductType() {
return mProductType;
}
public void setmProductType(String mProductType) {
this.mProductType = mProductType;
}
public String getmRetailerid() {
return mRetailerid;
}
public void setmRetailerid(String mRetailerid) {
this.mRetailerid = mRetailerid;
}
#Override
public String toString() {
return + mProductType + ","
+ mRetailerid +; //Remove "[" this..
}
And,
ArrayList<RetailerNames> retailerNamesList = (ArrayList<RetailerNames>) getIntent().getExtras().getSerializable("ProductsDetailsDescriptionPage");
System.out.println("The retailer details are"+" "+retailerNamesList);
Now try
Object temp[]=retailerNamesList.toArray();
String[] values=temp.toString().split(",");
String names=values[0];
String names=values[1];
I want to generate custom getters and setter, so I can handle variables better when I will be saving these instances into SQL database. I want to generate something like:
public class Test extends SQLEntry {
private static final String NAME = "Name";
public String getName() {
return get(NAME);
}
public void setName(String name) {
set(NAME, name);
}
}
But as I can see in Eclipse it generates only the following code:
public class Test {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Is there some plugin, that can do it? Or am I missing something?
I have like 20 classes and I will not write this manually.
I dont know why you need this, but here is the approach to custom Getters and Setters.
You can update all generated setters and getters by going to preferences > java > Code Style > code Templates and selecting code then edit Getter body and Setter body and put this:
Getter body: return get(${field});
Setter body: set(${field}, ${param});
Let me know if that works
I recommend that instead of doing what you describe, you should use Spring Data. Specifically the BeanPropertyRowMapper class in the org.springframework.jdbc.core package will do what you want.
Read more in the Spring API documentation.
there is no other plugin available!
how can some plugin write code that is specific to your business logic!
you have to write the code manually for setters and getters in all the classes!
Try write-it-once. Template based code generator. You write custom template using Groovy, and generate file depending on java reflections. It's the simplest way to generate any file. You can make getters/settest/toString by generating AspectJ or java files, SQL based on JPA annotations, inserts / updates based on enums and so on.
On the end I found it that it is the best to do it your self...
If you like writing a code than you will enjoy this solution the most.
public class CodeGenerator {
private final static String ENCODING = "UTF-8";
private final static String FILE_NAME = "File.txt";
public static void main(String[] args) {
try {
ArrayList<Carriage> names = getNames();
for (Carriage c : names) {
createSetter(c.name, c.capitalName);
createGetter(c.name, c.capitalName);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private static ArrayList<Carriage> getNames() throws FileNotFoundException {
File file = new File("/");
InputStream is = CodeGenerator.class.getResourceAsStream(FILE_NAME);
Scanner s = new java.util.Scanner(is, ENCODING).useDelimiter("\\A");
String content = s.next();
String[] lines = content.split(System.getProperty("line.separator"));
ArrayList<Carriage> ret = new ArrayList<Carriage>();
for (String line : lines) {
line = line.replaceAll("\\r", "");
int firstCapitalIndex = line.indexOf("String") + 7;
int secondCapitalIndex = line.indexOf(" ", firstCapitalIndex);
int firstIndex = line.indexOf("\"") + 1;
int secondIndex = line.indexOf("\"", firstIndex + 1);
Carriage c = new Carriage();
c.name = line.substring(firstIndex, secondIndex);
c.capitalName = line.substring(firstCapitalIndex, secondCapitalIndex);
ret.add(c);
}
return ret;
}
public static void createSetter(String name, String capitalName) {
String str = "public void set" + name + "(String val) {\n"
+ "\tset(" + capitalName + ", val);\n"
+ "}\n";
System.out.println(str);
}
public static void createGetter(String name, String capitalName) {
String str = "public String get" + name + "() {\n"
+ "\treturn (String) get(" + capitalName + ");\n"
+ "}\n";
System.out.println(str);
}
carriage:
package codegenerator;
public class Carriage {
public String name;
public String capitalName;
}
And to File.txt I just coppy all defined constants and run the generator...
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String EMAIL = "Email";
public static final String ADDRESS_1 = "Address1";
public static final String ADDRESS_2 = "Address2";
public static final String ADDRESS_3 = "Address3";
public static final String ICO = "Ico";
public static final String DIC = "Dic";
public static final String ADMIN_LOGIN = "AdminLogin";
public static final String ADMIN_PASSWORD = "AdminPassword";
public static final String LANGUAGE = "Language";
public static final String CODE = "CODE";
public static final String MONTHLY_PAYMENT = "MonthlyPayment";