UML class diagram implementation Address-Addressbook - java

I have 2 class diagrams, class Address
+forename
+surename
+street
+houseno
+code
+state
+toString
second Addressbook
insert(address: Address)
toString()
searchSurename (surename: string): Address[*]
+searchForename(forename: string): Address[*]
i implemented address:
public class Address {
public static String forename;
public static String surename;
public static String street;
public static int houseno;
public static int code;
public static String state;
public String toString(){
return this.forename + this.surename + this.street + this.houseno + this.code + this.state;
}
How can I implement Addressbook as easy as possible?
EDIT:
public class addressbook{
private static ArrayList<Address> book;
public addressbook(){
book = new ArrayList<Address>();
}
}
EDIT QUESTION:
Am I allowed to add new methods or attributes in a implementation outside the ones that we use in our class diagrams?
EDIT 2:
First try implementing method searchSurename with an ArrayList:
public static String searchSurename(String surename){
boolean exist = false;
if(this.addresses.isEmpty()){
return null;
}
for(int i=0;i<this.addresses.size();i++) {
if(this.addresses.get(i).getSurename() == surename) {
exist=true;
break;
}
if(exist) {
return this.addresses.get(surename);
} else {
return this.addresses.get(surename);
}
}
// return ?!?
}
The Program give me Errors at "this" at any line, maybe a mistake but I cant tell! It Looks a Little bit too difficult, I don't find any implementations where searching through a list is simple.

You could implement it in a way like this. Look at the api for arrayList for using its methods.
public class Adressbook {
List<Adress> adresses = new ArrayList<Adress>();
public Adressbook(){
adresses = new arraylist<Adress>();
}
public insert (Adress adress){
adresses.add(adress)
}
public searchSurename(String Surename){
}
public searchForename(String forename){
}
public String toString(){
}
ArrayList api:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

To have unique address use set collection interface
public class Adressbook {
....
private Set<Adress> adresses = null;
public Adressbook(){
adresses = new HashSet<Adress>();
}
public void add(Adress adress){
adresses.add(adress)
}
...
}

Related

Is it correct to have static factory method to get a new instance with one field updated?

I think the title is self-descriptive but I will give an example to elaborate on my question. I have a DTO class with few fields (a CarDataTransferObj class in my example). In another class (let's call it class A) I need to create a new instance of that object few times, but with only one field updated (length field in my example). Given DTO must be immutable in class A. As there is "many" fields in the class CarDataTransferObj, I thought about following approach (to avoid repeating code in class A):
#Builder
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public static CarDataTransferObj newInstanceWithUpdatedLength(final CarDataTransferObj car, final Integer newLength) {
return CarDataTransferObj.builder()
.id(car.getId())
.color(car.getColor())
.manufacturer(car.getManufacturer())
.model(car.getModel())
.uniqueIdNr(car.getUniqueIdNr())
.nrOfDoors(car.getNrOfDoors())
.engineType(car.getEngineType())
.length(newLength)
.safetyLevel(car.getSafetyLevel())
.build();
}
}
For me it smells like a little anti-pattern usage of static factory methods. I am not sure whether it's acceptable or not, hence the question.
Is using static factory method in the presented way an anti-pattern, and should be avoided ?
In my searching, I didn't come across anyone calling this1 an anti-pattern.
However, it is clear that if you try to do this using a classic builder that is not specifically implemented to support this mode of operation .... it won't work. For instance, the example CarBuilderImpl in the Wikipedia article on the Builder design pattern puts the state into an eagerly created Car instance. The build() method simply returns that object. If you tried to reuse that builder in the way that you propose, you would end up modifying a Car that has already been built.
There is another problem you would need to worry about. In we modified the Wikipedia CarBuilder example to add actual wheels (rather than a number of wheels) to the Car being built, we have to worry about creating cars that share the same wheels.
You could address these things in a builder implementation, but it is unclear whether the benefits out-weigh the costs.
If you then transfer this thinking to doing this using a factory method, you come to a slightly different conclusion.
If you are doing this as a "one-off", that's probably OK. You have a specific need, the code is clunky ... but so is the problem.
If you needed to do this for lots of different parameters, or combinations of parameters, this is not going to scale.
If the objects that are created are mutable, then this approach is could be problematic in a multi-threaded environment depending on how you control access to the objects you are using as templates.
1 - There are no clear measurable criteria for whether something is an anti-pattern or not. It is a matter of opinion. Admittedly, for many anti-patterns, there will be wide-scale agreement on that opinion.
It seems a little inefficient to construct an entirely new instance via a builder every time you want to make a new copy with a small modification. More significantly, it sounds like the places where you need the class to be immutable are isolated to places like class A. Why not try something like this:
public interface ICarDataTransferObject {
public Integer GetId();
public String GetColor();
public String GetManufacturer();
public String GetModel();
public String GetUUID();
public Integer GetDoorCount();
public EngineType GetEngineType();
public Integer GetLength();
public Integer GetSafteyLevel();
}
public class CarDataTransferObject Implements ICarDataTransferObject {
private Integer _id;
private String _color;
private String _manufacturer;
private String _model;
private String _uniqueIdNr;
private Integer _nrOfDoors;
private EngineType _engineType;
private Integer _length;
private Integer _safetyLevel;
public Integer GetId() { return _id; }
public void SetId(Integer id) { _id = id; }
public String GetColor() { return _color; }
public void SetColor(String color) { _color = color; }
public String GetManufacturer() { return _manufacturer; }
public void SetManufacturer(String manufacturer) { _manufacturer = manufacturer; }
public String GetModel() { return _model; }
public void SetModel(String model) { _model = model; }
public String GetUUID() { return _uniqueIdNr; }
public void SetUUID(String uuid) { _uniqueIdNr = uuid; }
public Integer GetDoorCount() { return _nrOfDoors; }
public void SetDoorCount(Integer count) { _nrOfDoors = count; }
public EngineType GetEngineType() { return _engineType; }
public void SetEngineType(EngineType et) { _engineType = et; }
public Integer GetLength() { return _length; }
public void SetLength(Integer length) { _length = length; }
public Integer GetSafteyLevel() { return _safetyLevel; }
public void SetSafteyLevel(Integer level) { _safteyLevel = level; }
public CarDataTransferObject() {}
public CarDataTransferObject(ICarDataTransferObject other) { ... }
public ReadOnlyCarDataTransferObject AsReadOnly() {
return ReadOnlyCarDataTransferObject (this);
}
}
}
public class ReadOnlyCarDataTransferObject Implements ICarDataTransferObject {
private ICarDataTransferObject _dto = null;
public Integer GetId() { return _dto.GetId(); }
public String GetColor() { return _dto.GetColor(); }
public String GetManufacturer() { return _dto.GetManufacturer(); }
public String GetModel() { return _dto.GetModel(); }
public String GetUUID() { return _dto.GetUUID(); }
public Integer GetDoorCount() { return _dto.GetDoorCount(); }
public EngineType GetEngineType() { return _dto.GetEngineType(); }
public Integer GetLength() { return _dto.GetLength(); }
public Integer GetSafteyLevel() { return _dto.GetSafteyLevel; }
public ReadOnlyCarDataTransferObject (ICarDataTransferObject other) {
_dto = other;
}
}
Now when you want class A to have a copy no one can modify, just use the copy constructor and only expose a ReadOnly version of that copy.
public class A {
ICarDataTransferObject _dto;
ReadOnlyCarDataTransferObject _readOnlyDTO;
public ICarDataTransferObject GetDTO() { return _readOnlyDTO; }
public A(ICarDataTransferObject dto) {
_dto = new CarDataTransferObject(dto);
_readOnlyDTO = new ReadOnlyCarDataTransferObject(_dto);
}
}
You commonly see this approach in .NET applications.
While it is debatable whether your static method is an anti-pattern or not, it surely won't scale for combinations of different attributes. Nonetheless, even if it's not an anti-pattern, I think there is a better way to accomplish what you need.
There's a variant of the traditional builder pattern that, instead of creating a new empty builder, accepts an already built object and creates an already initialized builder. Once you create the builder this way, you simply change the length attribute in the builder. Finally, build the object. In plain code (no Lombok, sorry) it could be like this:
public class CarDataTransferObj {
private Integer id;
private String color;
// other attributes omitted for brevity
private Integer length;
// Private constructor for builder
private CarDataTransferObj(Builder builder) {
this.id = builder.id;
this.color = builder.color;
this.length = builder.length;
}
// Traditional factory method to create and return builder
public static Builder builder() {
return new Builder();
}
// Factory method to create and return builder initialized from an instance
public static Builder builder(CarDataTransferObj car) {
Builder builder = builder();
builder.id = car.id;
builder.color = car.color;
builder.length = car.length;
return builder;
}
// getters
public static class Builder {
private Integer id;
private String color;
private Integer length;
private Builder() { }
public Builder withId(Integer id) { this.id = id; return this; }
public Builder withColor(String color) { this.color = color; return this; }
public Builder withLength(Integer length) { this.length = length; return this; }
public CarDataTransferObj build() {
return new CarDataTransferObj(this);
}
}
}
Now with all this infrastructure in place, you can do what you want as easy as:
CarDataTransferObj originalCar = ... // get the original car from somewhere
CarDataTransferObj newCar = CarDataTransferObj.builder(originalCar)
.withLength(newLength)
.build();
This approach has the advantage that it scales well (it can be used to change any combination of parameters). Maybe all this builder's code seems boilerplate, but I use an IntelliJ plugin to create the builder with two keystrokes (including the variant factory method that accepts a built instance to create an initialized builder).
I'm still new to java but..
I guess making a copy method which takes the CarDataTransferObj object variables and sets their values to another CarDataTransferObj object variables and changing the the length using it's setter method would be better idea
Example:
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public void Copy(CarDataTransferObj copy) { //Could add another parameter here to be the new length
copy.setId(id);
copy.set(color);
copy.setManufacturer(manufacturer);
copy.setModel(model);
copy.setUniqueIdNr(uniqueIdNr));
copy.setNrOfDoors(nrOfDoors));
copy.setEngineType(engineType));
copy.setLength(length);
copy.setSafetyLevel(safetyLevel));
}
}
public class SomeOtherClass {
CarDataTransferObj car1 = new CarDataTransferObj(); //Using this way made you able to use the constructor for a more useful thing
//You set the variables you want for car1 here
CarDataTransferObj car2 = new CarDataTransferObj();
car1.Copy(car2)
car2.setLength(newLength) //Set the new length here
}

Possible to convert ArrayList<String> to ArrayList<CustomModel>?

I'm saving some ArrayList in Sharedpreferences. But I want to set my custom model to ArrayList in adapter cause get items with getter. I really tired too many solutions from stackoverflow but I couldn't do that.
private ArrayList<String> fullList = new ArrayList<>();
to
private ArrayList<MyCustom> fullList = new ArrayList<>();
My Custom Class:
public class InstagramUserSummary implements Serializable {
public boolean is_verified;
public String profile_pic_id;
public boolean is_favorite;
public boolean is_private;
public String username;
public long pk;
public String profile_pic_url;
public boolean has_anonymous_profile_picture;
public String full_name;
#Override
public int hashCode() {
return Objects.hash(username, pk);
}
#Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof InstagramUserSummary)) {
return false;
}
InstagramUserSummary user = (InstagramUserSummary) obj;
return pk == user.getPk();
}}
List coming like this:
[InstagramUserSummary(super=dev.niekirk.com.instagram4android.requests.payload.InstagramUserSummary#a4acf205, is_verified=false, profile_pic_id=1773528799482591987_1654599017, is_favorite=false, is_private=false, username=ququletta, pk=1654599017, profile_pic_url=https://instagram.fada1-5.fna.fbcdn.net/vp/8d99014623ed527e52512a20002d884b/5C387E45/t51.2885-19/s150x150/31203725_200759604054857_5778864946146181120_n.jpg, has_anonymous_profile_picture=false, full_name=Ququletta)]
Thanks.
First of all, there is no need to have the username field be a public member of the MyCustom class. Since you're exposing access to the field via getters/setters having it public is wrong.
Aside from that, you can easily use streams and a mapping function to create a new MyCustom instance from a Stream of String.
In order to avoid boilerplate code, I would go ahead and create a static creator method in MyCustom like this:
public class MyCustom {
private String userName;
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public static MyCustom from(final String userName) {
MyCustom custom = new MyCustom();
custom.setUserName(userName);
return custom;
}
}
And then I would use this as a method reference to convert Strings over to MyCustoms thus collecting them into a new list like this:
List<String> list = new ArrayList<>();
List<MyCustom> customs = list.stream()
.map(MyCustom::from)
.collect(Collectors.toList());
Finally, also avoid initializing lists using the concrete type (e.g. ArrayList<String> someList = new ArrayList<>;'. It's much better to code the interfaces, thus doing something like List<String> someList = new ArrayList<>.
Solution:
Suppose you have a String variable in MyCustom class, like:
public class MyCustom {
private String strName;
public MyCustom(String name) {
this.strName = name;
}
public void setName(String name) {
this.strName = name;
}
public String getName() {
return this.strName;
}
}
then, you can do something like this:
for (MyCustom value : fullList) {
customFullList.add(new MyCustom(value))
}
Hope it helps.

Is there any default method for ENUM? [duplicate]

What is the best way to use the values stored in an Enum as String literals?
For example:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3
}
Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.mode1.toString().
You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...
Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.
String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.
Option Two: add overriding properties to your enums if you want more control
public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");
private final String name;
private Modes(String s) {
name = s;
}
public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}
Option Three: use static finals instead of enums:
public final class Modes {
public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";
private Modes() { }
}
Option Four: interfaces have every field public, static and final:
public interface Modes {
String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}
Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?
String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);
There's also a static valueOf(Class, String) on Enum itself, so you could also use:
Modes mode = Enum.valueOf(Modes.class, name);
You could override the toString() method for each enum value.
Example:
public enum Country {
DE {
#Override
public String toString() {
return "Germany";
}
},
IT {
#Override
public String toString() {
return "Italy";
}
},
US {
#Override
public String toString() {
return "United States";
}
}
}
Usage:
public static void main(String[] args) {
System.out.println(Country.DE); // Germany
System.out.println(Country.IT); // Italy
System.out.println(Country.US); // United States
}
As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:
public enum Country{
SPAIN("EspaƱa"),
ITALY("Italia"),
PORTUGAL("Portugal");
private String value;
Country(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return this.getValue();
}
}
You could also add a static method to retrieve all the fields, to print them all, etc.
Simply call getValue to obtain the string associated to each Enum item
mode1.name() or String.valueOf(mode1). It doesn't get better than that, I'm afraid
public enum Modes {
MODE1("Mode1"),
MODE2("Mode2"),
MODE3("Mode3");
private String value;
public String getValue() {
return value;
}
private Modes(String value) {
this.value = value;
}
}
you can make a call like below wherever you want to get the value as a string from the enum.
Modes.MODE1.getvalue();
This will return "Mode1" as a String.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
You can use Mode.mode1.name() however you often don't need to do this.
Mode mode =
System.out.println("The mode is "+mode);
As far as I know, the only way to get the name would be
Mode.mode1.name();
If you really need it this way, however, you could do:
public enum Modes {
mode1 ("Mode1"),
mode2 ("Mode2"),
mode3 ("Mode3");
private String name;
private Modes(String s) {
name = s;
}
}
my solution for your problem!
import java.util.HashMap;
import java.util.Map;
public enum MapEnumSample {
Mustang("One of the fastest cars in the world!"),
Mercedes("One of the most beautiful cars in the world!"),
Ferrari("Ferrari or Mercedes, which one is the best?");
private final String description;
private static Map<String, String> enumMap;
private MapEnumSample(String description) {
this.description = description;
}
public String getEnumValue() {
return description;
}
public static String getEnumKey(String name) {
if (enumMap == null) {
initializeMap();
}
return enumMap.get(name);
}
private static Map<String, String> initializeMap() {
enumMap = new HashMap<String, String>();
for (MapEnumSample access : MapEnumSample.values()) {
enumMap.put(access.getEnumValue(), access.toString());
}
return enumMap;
}
public static void main(String[] args) {
// getting value from Description
System.out.println(MapEnumSample.getEnumKey("One of the fastest cars in the world!"));
// getting value from Constant
System.out.println(MapEnumSample.Mustang.getEnumValue());
System.out.println(MapEnumSample.getEnumKey("One of the most beautiful cars in the world!"));
System.out.println(MapEnumSample.Mercedes.getEnumValue());
// doesnt exist in Enum
System.out.println("Mustang or Mercedes, which one is the best?");
System.out.println(MapEnumSample.getEnumKey("Mustang or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mustang, which one is the best?") + " is the best!.");
// exists in Enum
System.out.println("Ferrari or Mercedes, wich one is the best?");
System.out.println(MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") + " is the best!");
}
}
You can simply use:
""+ Modes.mode1
public enum Environment
{
PROD("https://prod.domain.com:1088/"),
SIT("https://sit.domain.com:2019/"),
CIT("https://cit.domain.com:8080/"),
DEV("https://dev.domain.com:21323/");
private String url;
Environment(String envUrl) {
this.url = envUrl;
}
public String getUrl() {
return url;
}
}
String prodUrl = Environment.PROD.getUrl();
It will print:
https://prod.domain.com:1088/
This design for enum string constants works in most of the cases.
Enum is just a little bit special class. Enums can store additional fields, implement methods etc. For example
public enum Modes {
mode1('a'),
mode2('b'),
mode3('c'),
;
char c;
private Modes(char c) {
this.c = c;
}
public char character() {
return c;
}
}
Now you can say:
System.out.println(Modes.mode1.character())
and see output:
a
package com.common.test;
public enum Days {
monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");
private int id;
private String desc;
Days(int id,String desc){
this.id=id;
this.desc=desc;
}
public static String getDay(int id){
for (Days day : Days.values()) {
if (day.getId() == id) {
return day.getDesc();
}
}
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
};
This method should work with any enum:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public int getValue() {
return this.ordinal();
}
public static DataType forValue(int value) {
return values()[value];
}
public String toString() {
return forValue(getValue()).name();
}
}
i found this one is more easy for preventing type error:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
String str;
Modes(){
this.str = super.name();
}
#Override
#NonNull
public String toString() {
return str;
}
however - this may work when you need to use a String on a log/println or whenever java compiles the toString() method automatically, but on a code line like this ->
// sample method that require (string,value)
intent.putExtra(Modes.mode1 ,shareElement.getMode()); // java error
// first argument enum does not return value
instead as mentioned above you will still have to extend the enum and use .name() in those cases like this:
intent.putExtra(Modes.mode1.name() ,shareElement.getMode());
after many tries I have come with this solution
public static enum Operation {
Addition, Subtraction, Multiplication, Division,;
public String getUserFriendlyString() {
if (this==Addition) {
return " + ";
} else if (this==Subtraction) {
return " - ";
} else if (this==Multiplication) {
return " * ";
} else if (this==Division) {
return " / ";
}
return "undefined";
}
}
You can try this:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
public String toString(){
switch(this) {
case some-really-long-string:
return "some-really-long-string";
case mode2:
return "mode2";
default: return "undefined";
}
}
}
use mode1.name() or String.valueOf(Modes.mode1)

How to call a method in another class in Java?

Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.
classroom.java
public class classroom {
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName) {
classRoomName = newClassRoomName;
}
public String returnClassRoomName() {
return classRoomName;
}
public void setTeacherName(String newTeacherName) {
teacherName = newTeacherName;
}
public String returnTeacherName() {
return teacherName;
}
}
School.java
import java.util.ArrayList;
public class School {
private ArrayList<classroom> classrooms;
private String classRoomName;
private String teacherName;
public School() {
classrooms = new ArrayList<classroom>();
}
public void addClassRoom(classroom newClassRoom, String theClassRoomName) {
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
// how to write a method to add a teacher to the classroom by using the
// classroom parameter
// and the teachers name
}
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
Try this :
public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
myClassRoom.setTeacherName(TeacherName);
}
class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}
in School,
public void addTeacherName(classroom classroom, String teacherName) {
classroom.setTeacherName(teacherName);
}
BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom> to map a classroom name to a classroom.
Then, if you use my suggestion, this would work
public void addTeacherName(String className, String teacherName) {
classrooms.get(className).setTeacherName(teacherName);
}
Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

Searching in an Arraylist

Currently I have two classes. A Classroom class and a School class. I would like to write a method in the School class public void showClassRoomDetails which would find the classroom details by only using the teacherName.
e.g.
teacherName = Daniel className = Science
teacherName = Bob className = Maths
so when I input Bob, it would print out Bob and Maths
many, thanks
public class Classroom
{
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName)
{
classRoomName = newClassRoomName;
}
public String returnClassRoomName()
{
return classRoomName;
}
public void setTeacherName(String newTeacherName)
{
teacherName = newTeacherName;
}
public String returnTeacherName()
{
return teacherName;
}
}
import java.util.ArrayList;
public class School
{
private ArrayList<Classroom> classrooms;
private String classRoomName;
private String teacherName;
public School()
{
classrooms = new ArrayList<Classroom>();
}
public void addClassRoom(Classroom newClassRoom, String theClassRoomName)
{
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
public void addTeacherToClassRoom(int classroomId, String TeacherName)
{
if (classroomId < classrooms.size() ) {
classrooms.get(classroomId).setTeacherName(TeacherName);
}
}
public void showClassRoomDetails
{
//loop
System.out.println(returnClassRoomName);
System.out.println(returnTeacherName);
}
}
Do you really need a list here ?
A Map holding classroom - teacher associations would be more helpful for what you're trying to achieve.
But there are also strange things in your code: for instance, why do you hold a classRoomName and teacherName as instance variables in your School class ?
Change your method signature to take a targetTeacherName as a parameter. Loop through the classrooms until you find one with that teacher. Output the information of that classroom.
Since you are using an ArrayList you could simply use a for each statement:
public void showClassRoomDetails(String teacherName)
{
for (Classroom classroom : this.classrooms)
{
if (classroom.returnTeacherName().equals(teacherName))
{
System.out.println(classroom.returnClassRoomName());
System.out.println(classroom.returnTeacherName());
break;
}
}
}
As a small suggestion, do not name your methods returnXxx(), use getXxx() instead, it is the standard Javabean convention.

Categories