Set & Get Methods

jdurdach :

Java I student here!

I am having a hard time understanding how to make set and get methods. I am working on a question in my textbook Java Programming, 9th Edition independently and I am asked to do the following:

"Create a class named Sandwich. Data fields include a String for the main ingredient (such as tuna), a String for bread type (such as wheat), ad a double for price (such as 4.99). Include methods to get and set values for each of these fields."

It then asks me to do this:

"Create an application named TestSandwich that instantiates one Sandwich object and demonstrates the use of the set and get methods."

So for the first part, I made a .java file with the following code:

public class Sandwich {
private String ingredient;
private String bread;
private double price;

public Sandwich(String ing, String bre, double pri) {
    ingredient = ing;
    bread = bre;
    price = pri;
}

public void setIngredient(String ing) {
    this.ingredient = ing;
}

public String getIngredient() {
    return ingredient;
}
public String getBread() {
    return bread;
}
public Double getPrice() {
    return price;
}
}

For the second part, I did the following:

import java.util.Scanner;
public class TestSandwich {
public static void main(String[] args) {
    String Ingredient;
    String Bread;
    Double Price;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("MAKE A SANDWICH");
    System.out.println("Enter an ingredient:  ");
    Ingredient = keyboard.nextLine();
    System.out.println("Enter bread:  ");
    Bread = keyboard.nextLine();
    System.out.println("Enter a price");
    Price = keyboard.nextDouble();

    Sandwich obj = new Sandwich(Ingredient, Bread, Price);

    System.out.println("The ingredient is " + obj.getIngredient());
    System.out.println("The bread is " + obj.getBread());
    System.out.println("The price is " + obj.getPrice());       
}
}

I completed this and it works well, however I realize that I did not create any set methods. Could someone explain to me a better way to do this according to the directions? I'm sure that this way works but I would like to do it by the book and be able to understand it better. I'm not sure where to start with creating the set methods. Please let me know. Thanks so much!

PS: This is NOT homework, I'm just trying to understand this a little better.

-Mark

GhostCat salutes Monica C. :

Simple go like:

System.out.println("Enter another price");
double newPrice = keyboard.nextDouble();
obj.setPrice(newPrice);

and print your obj before / after that call (and of course: @Overwrite toString() on that class to get meaningful output).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88902&siteId=1