I have this java class assignment, it inputs crew members and display their info, I've done other similar cases, but not sure how to construct this one.
I'm to create two classes, Sailor and CrewMember that works with this main method-
import java.util.ArrayList;
public class SailorProgram {
public static void main(String[] args) {
Sailor firstSailor = new Sailor("Jimmy", "jimmy#mail.com");
Sailor secondSailor = new Sailor("Rose", "rose#mail.com");
Sailor thirdSailor = new Sailor("James", "james#sailors.com");
CrewMember firstCrew = new CrewMember();
CrewMember secondCrew = new CrewMember();
firstCrew.addCrewMember(firstSailor);
firstCrew.addCrewMember(secondSailor);
secondCrew.addCrewMember(thirdSailor);
secondCrew.addCrewMember(secondSailor);
System.out.println(" First crew \n" + firstCrew);
System.out.println(" Second crew \n" + secondCrew);
secondSailor.setEmail("Rose#sailors.com");
System.out.println(" Second crew \n" + secondCrew);
}
}
then prints out
First crew
Jimmy (jimmy#mail.com)
Rose (rose#mail.com)
Second crew
James (james#sailors.com)
Rose (rose#mail.com)
Second crew
James (james#sailors.com)
Rose (rose#sailors.com)
thanks!
addCrewMember() is the key method we want to know. If you give the Sailor reference to the secondCrew class,the output will change.
public class Sailor {
private String name;
private String email;
public Sailor(String name, String email) {
this.name = name;
this.email = email;
}
#Override
public String toString() {return name + " " + "(" + email + ")";}
}
If the CrewMember.class Like This below
import java.util.ArrayList;
public class CrewMember {
private final ArrayList<Sailor> sailors = new ArrayList<>();
public void addCrewMember(Sailor s) { //add sailors with this
sailors.add(s);
}
#Override
public String toString() { return sailors.toString(); }
}
And run your main method in your question
thr output is this:
First crew
[Jimmy (jimmy#mail.com), Rose (rose#mail.com)]
Second crew
[James (james#sailors.com), Rose (rose#mail.com)]
Second crew
[James (james#sailors.com), Rose (Rose#sailors.com)]
Rose#sailors.com is change! because the ArrayList sailors save the reference of the Rose Sailor
The question isn't exactly clear but I will make some assumptions. First, your CrewMember class holds sailors, so a more appropriate name would be Crew. The way you can implement this is with an ArrayList<Sailor> for example.
class Crew {
private final ArrayList<Sailor> sailors = new ArrayList<>();
//other things, like constuctor here, if needed
public void addCrewMember(Sailor s) { //add sailors with this
sailors.add(s);
}
}
Then your Sailor class is very simple.
class Sailor {
private String name;
private String email;
public Sailor(String name, String email) {
this.name = name; this.email = email;
}
//other methods, like getters here
}
Edit: I noticed you need to print the objects as well. For this you can use the Object class' toString method. An example for your Sailor class:
#Override
public String toString() {
return name + ", " + email;
}
Using System.out.println(sailor1) will invoke this method on sailor1.
Related
Sailor class
public class Sailor {
private String name;
private String email;
public Sailor(String name, String email) {
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Crew class
import java.util.ArrayList;
public class Crew {
private ArrayList<Sailor> sailorList = new ArrayList<>();
public Crew() {
}
public void addCrewMember(Sailor sailor) {
sailorList.add(sailor);
}
public String toString() {
String str = "";
for(int i = 0; i < sailorList.size(); i++) {
str = sailorList.get(i).getName() + sailorList.get(i).getEmail();
}
return str;
}
}
Main program
public class ObjectsSailorProgram {
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);
}
}
I am having trouble printing the crews and I'm not sure if the addCrewMember is correct.
I've tried reading other similar posts but i haven't been able to use the solutions here. So i need help with the addCrewMember and toString methods
You aren't setting the variables neither in constructor nor by calling setters in your main.
You can change the constructor as below:
public Sailor(String name, String email) {
this.name = name;
this.email = email;
}
In your toString() method, you're overwriting the str. Use StringBuilder to append strings into the resulting string. You can modify your toString() method as follows:
public String toString() {
StringBuilder str = new StringBuilder();
for(int i = 0; i < sailorList.size(); i++) {
str.append(i+1)
.append(". ")
.append(sailorList.get(i).getName())
.append(" ")
.append(sailorList.get(i).getEmail())
.append("\n");
}
return str.toString();
}
And your program will give the output:
=== First crew ===
1. Frank frank#mail.com
2. Susan susan#mail.com
3. Ann ann#sailors.com
=== Second crew ===
1. John john#sailors.com
2. Susan susan#mail.com
=== Second crew ===
1. John john#sailors.com
2. Susan Susan#sailors.com
0> sailor's constructor is wrong-> you're not initializing the data
public Sailor(String name, String email) {
setEmail(email); //or this.email=email;
this.name=name; //you may make a setter also for this
}
1> private ArrayList<Sailor> sailorList = new ArrayList<Sailor>();
2> the to-string is also wrong: it prints just the last sailor, use += instead of =
str +=" "+ sailorList.get(i).getName() + sailorList.get(i).getEmail();
This is just personal taste: I prefer "for-each" syntax.
for(Sailor s: sailorList){
out += s.getName()+" "+s.getEmail();
}
As others have noted, you are not assigning the values in your Sailor constructor so do that. You should also add any missing get/set methods.
public Sailor(String name, String email) {
this.name = name;
this.email = email;
}
The addCrewMember(Sailor) method in Crew looks correct but your toString() method is flawed.
You are trying to build a String but you are re-assigning it on each iteration rather then concatenating elements on each iteration.
Except in very simple cases, you should avoid String concatenation when compose Strings.
The code is pushing all of the elements together with no separation which means you will have an unreadable blob of characters (e.g. bobsmithbsmith#boat.comsamsmithssmith#boat.com)
I would suggest that you write a toString() in Sailor class. This example separates the elements of Sailor by commas and wraps the entire entity in curly braces (e.g. "{Sam Smith, ssmith#boat.com}"). Note the use of String.format(..) rather than concatenation.
public class Sailor {
... stuff ...
#Override public String toString() {
return String.format("{%s, %s}", name, email);
}
}
The Crew.toString() method can employ this to compose its String. The following makes use of the StringJoiner class to compose a comma-separated list of elements wrapped in square braces to represent the crew members (e.g. "[{Al Almond, aalmond#boat.com},{Bob Bobson, bbobson#boat.com}]");
public class Crew {
... stuff ...
#Override public String toString() {
StringJoiner sj = new StringJoiner(",", "[", "]");
for (Sailor s : sailorList) {
sj.add(s.toString()); // Sailor.toString() is explicitly invoked here but you could remove that call and it should still be invoked implicitly
}
return sj.toString();
}
}
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 4 years ago.
I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this.
I've been using python for quite a while now so I'm used to using a dynamic language.
Please see some code I've been playing around with below:
import java.util.Scanner;
class MyClass {
static String myName(String name) {
return ("Your name is: "+name);
}
static String myAge(Integer age){
return ("Your age is: "+age);
}
static String myGender(String gender){
return ("You are: "+gender);
}
}
class Test{
public static void main(String [ ] args){
Scanner ui = new Scanner(System.in);
MyClass user = new MyClass();
//Output with new variable of class - user
String input = ui.next();
String newname = user.myName(input);
System.out.println(newname);
//Output calling class directly
Integer input1 = ui.nextInt();
String newage = MyClass.myAge(input1);
System.out.println(newage);
//Output with new variable of class - user
String input2 = ui.next();
String newgender = MyClass.myGender(input2);
System.out.println(newgender);
}
}
Thanks for your time.
If everything in the class is static (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this:
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
String myName() { return "Your name is: " + name; }
String myAge() { return "Your age is: " + age; }
String myGender() { return "You are: " + gender; }
}
Then you could create several Person instances with different internal state and use them interchangeably in your code:
public static void main(String[] args) {
Person jim = new Person("Jim", 40, "male");
Person sally = new Person("Sally", 12, "female");
report(jim);
report(sally);
}
private static report(Person person) {
System.out.println(person.myName());
System.out.println(person.myAge());
System.out.println(person.myGender());
}
If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it
Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike
This question already has answers here:
Setter methods or constructors
(10 answers)
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
In the below code I've already declared that room = r; subject = s; and time = t; in the user defined constructor, so why is it necessary to do so again in set methods, my lecturer specifically asked that we add set methods for the room subject and time but it's redundant code as when I comment it out it still works. Do you only need to include set methods when there is no used defined constructor? What could be the advantage of having them set methods there?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
The constructor "initializes" your values.
Let's say you have...
public class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String str;
str = "My name is "+name+" and I am "+age+" years old!";
return str;
}
}//End of Person
public class Main {
public static void main(String [] args) {
Person person = new Person("Bob", 15);
System.out.println(person.toString());
System.out.println("Switching my name...");
person.setName("Joe");
System.out.println(person.toString());
}
}//End of main
You see the difference? You should use the constructor if you want to create a new instance of the object. This way, you can set all the fields of the object at once and not need to call 490832490 setters (in this case, one for name and one for age...). You then can use the setter approach when you want to change the value of a field, PRIOR TO the object been created.
I DID ALL THIS ON THIS FORUM SO I MIGHT HAVE SYNTAX ERRORS SO CAREFUL...DIDN'T USE AN IDE IF YOU WANT TO TEST IT
The set methods make your object mutable. If you don't have the set methods and your variables are private then the Object will be immutable. You won't be able to change the values after it is constructed...If the values need to change you would have to create a new Object.
"Setters" allow you to modify private attributes of your object after instantiating. For example:
Lecture l1 = new Lecture(140, "Comp", 5);
//Since "room" is private you can't write l1.room = 4
//and have to use the setter method instead:
l1.setroomNumber(4);
l1.display();
They are also very useful if you want to do something if an attribute changes.
Let's assume you are using Observers, then you could call notifyObservers() or setChanged() in your setter method and never have to worry about these methods not getting called if your attribute changes.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}
According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");
I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.
Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.