Javas setter method don't change email when needed - java

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.

Related

how can replace more then 16 if else-if statement Java

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.

Multiple values for a single parameter

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

If JComboBox is editable, how to cast the entered string to object?

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.

How do I create an object from another class (BlueJ)

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.

Confused about cloning in Java

I have this code in Java.
public class CloneTest implements Cloneable{
String name;
int marks;
public CloneTest(String s, int i) {
name = s;
marks = i;
}
public void setName(String s) {
name = s;
}
public void setMarks(int i) {
marks = i;
}
#Override
public Object clone() {
return new CloneTest(this.name, this.marks);
}
}
I have created one object of this class, and then cloned it. Now, when I change the value of name in one object, the value of name remains unchanged in the other. The strange thing here is in the constructor, I am just using a simple reference for name, not creating a new String for name. Now, since Strings are reference types, I expected the String in the clone to be changed as well. Can anyone tell me what's going on? Thanks in advance!
EDIT
Code Testing
CloneTest real = new CloneTest("Molly", 22);
CloneTest clone = real.clone();
real.setName("Dolly");
I used the "Inspect Variables" feature of BlueJ to check the values.
Assume that original is the name of original CloneTest object, and cloned is the cloned object that you created from original using the clone() method.
This is what happened:
1. Your cloned.name and original.name are pointing at the same object, which in this case was a String.
2. Then you asked your original.name to point to a different String object ("Dolly"). This happens when you assign the new String object ("Dolly") to the reference original.name.
3. But, the cloned.name still points to the first String object ("Dolly").
Hence, cloned.name still prints the 1st String object.
Now, if you are able to change the content of the String object without reassigning the references, then the change in clone.name will reflect in original.name. But for String objects, this is not possible due to the immutability of Strings. However, you can reflect the change from the clone to original with StringBuffers which are mutable strings so to speak. Take a look at this example code for the same: https://gist.github.com/VijayKrishna/5967668
Each instance of your class has different references to an object. You you're just changing reference not modifying object. If you place your string in some holder object, then clone it and set string inside the holder (not a holder reference but string reference inside holder) then you'll have your changes in both of clones
So are you saying you are doing something like:
public void testSomeMethod() {
CloneTest a = new CloneTest("a", 1);
CloneTest b = (CloneTest) a.clone();
a.setName("b");
assertFalse(b.name.equals(a.name));
assertEquals("b", a.name);
assertEquals("a", b.name);
}
?
If so, then all these assertions should pass. Your clone method has reference types in it, and when initially cloned, they refer to the same object. But the setName("...") changes the value that instance points to, not the value of the referred to object.
Get some better clarity along with #vijay answer by looking hash code.
CloneTest real = new CloneTest("Molly", 22);
CloneTest clone = (CloneTest) real.clone();
int h1=real.name.hashCode();
int h2=clone.name.hashCode();
System.out.println("h1 " + h1 + " h2 " + h2); // same
real.setName("sak");
h1=real.name.hashCode();
h2=clone.name.hashCode();
System.out.println("h1 " + h1 + " h2 " + h2); //different
Output :
h1 74525175 h2 74525175
h1 113629 h2 74525175
package com.test;
class Manager implements Cloneable
{
String firstName;
String lastName;
int age;
public Manager(String fname,String lname,int a)
{
this.firstName=fname;
this.lastName=lname;
this.age=a;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
public class TestCloning {
public static void main(String[] args) throws CloneNotSupportedException {
Manager m1=new Manager("Sadik","Tahir",26);
Manager m_clone=(Manager)m1.clone();
Manager m2=m1;
System.out.println("M1 Details:::");
System.out.println("Fisrt Name:"+m1.getFirstName()+",LastName:"+m1.getLastName()+",Age:"+m1.getAge());
System.out.println("Hashcode:"+m1.hashCode());
System.out.println("M_Clone Details:::");
System.out.println("Fisrt Name:"+m_clone.getFirstName()+",LastName:"+m_clone.getLastName()+",Age:"+m_clone.getAge());
System.out.println("Hashcode:"+m_clone.hashCode());
System.out.println("M2 Details:::");
System.out.println("Fisrt Name:"+m2.getFirstName()+",LastName:"+m2.getLastName()+",Age:"+m2.getAge());
System.out.println("Hashcode:"+m2.hashCode());
m1.setFirstName("Afreen");
m1.setLastName("Khan");
m1.setAge(25);
System.out.println("M1 Details:::");
System.out.println("Fisrt Name:"+m1.getFirstName()+",LastName:"+m1.getLastName()+",Age:"+m1.getAge());
System.out.println("Hashcode:"+m1.hashCode());
System.out.println("M_Clone Details:::");
System.out.println("Fisrt Name:"+m_clone.getFirstName()+",LastName:"+m_clone.getLastName()+",Age:"+m_clone.getAge());
System.out.println("Hashcode:"+m_clone.hashCode());
System.out.println("M2 Details:::");
System.out.println("Fisrt Name:"+m2.getFirstName()+",LastName:"+m2.getLastName()+",Age:"+m2.getAge());
System.out.println("Hashcode:"+m2.hashCode());
}
}

Categories