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.
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.
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.
When user submit the form I want to check multiple text fields in a form and check whether it is null or not and it must show which input field is blank
String A = request.getparameter("a");
String B = request.getparameter("b");
String C = request.getparameter("c");
if(A==null || B==null || C==null)
{
//Here I want to store the corresponding errors in an arrayfield and it should display which field is empty.
}
change the implementation to this thne
if(A==null){
//A is null, add message
}
else if(B==null){
//error message against B
}
else if(C==null){
//error message against C
}
Use Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
so it would be something like
if(StringUtils.isEmpty(A)){
}
// inside onCreate method do this
//make this variable globle
ArrayList<MyVariableNameValue> nullStringList=new ArrayList<>();
for (MyVariableNameValue nullString: checkNull()) {
Log.d("nullsize", "onCreate: "+nullString.getName());
}
//up to here
//create getter method class to store the variable name and value in mainactivity or outside it
public class MyVariableNameValue{
String name,value;
public MyVariableNameValue(String name,String value){
this.name=name;
this.value=value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
//create a method to return null variable values and name in maiactivity
public ArrayList<MyVariableNameValue> checkNull(){
nullStringList.clear();
String A = request.getparameter("a");
String B = request.getparameter("b");
String C = request.getparameter("c");
ArrayList<MyVariableNameValue> checkString = new ArrayList<>();
checkString.add(new MyVariableNameValue("A",A));
checkString.add(new MyVariableNameValue("B",B));
checkString.add(new MyVariableNameValue("C",C));
for (MyVariableNameValue myString: checkString) {
if(TextUtils.isEmpty(myString.getValue())){
nullStringList.add((myString));
}
}
return nullStringList;
}
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
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];