Touchpad Touchpad - 1 month ago 8
Java Question

Java Change attribute from driver class

I'm not sure if my professor mistyped the instruction or I just missed something. I am given an assignment and we're working on arraylist. A part of the instruction ask us to write in the class a method to change an attribute name city, a method called setCity(). After that I will create a driver class to ask users to search for the person who I want to change the city for. My professor replied but it was basically a repeat of the instruction. During the weekend there will be no replies until Monday.

I understand from the driver side how to write this method. But my question is how to write the setCity() method to change the city attribute in the main class?

Quote of the instruction: " Your CityEntry class should have a setCity() method that will allow the city attribute to be changed"

Example:

public static void editCity(ArrayList<CityEntry> address){
boolean found = false;
Scanner scan = new Scanner(System.in);
System.out.println("example: ");
String str = scan.nextLine();

for(int i = 0; i < address.size(); i++){
if(address.get(i).getName().equalsIgnoreCase(str)){
found = true;
}
}

if(found){
System.out.println("Enter new city: ");
//here's the problem. If I should create a method in the driver for setCity()
//can't think of how to create it in the CityEntry class
}
}


Would an example of setCity() method in the CityEntry class look like this?

public String setCity(city){
this.city = city;
return city;
}


Edit: Thanks everyone. I had forgotten the basics for mutators. We haven't been using it for majority of our assignments. So kind didn't know what the professor meant by it.

Answer

You are close, but in this case you don't need to return anything. All you need to do is change the city.

In Java, when we don't want to return anything, we use "void" as the type (the return void part is implied and left out).

So instead of

public String setCity(String city){

you will use

public void setCity(String city){

and don't return anything.