Java – set and get methods
Java I'm here student!
It's hard for me to understand how to set and get methods I am working independently in my textbook Java programming, 9th Edition. I am required to do the following:
"Create a class named sandwich. The data field includes the string of main ingredients (such as tuna), the string of bread type (such as wheat), and double the price (such as 4.99). It includes the methods to obtain and set the value of each field“
Then it asked me to do this:
"Create an application named testsandwich, which instantiates a sandwich object and demonstrates how to use the set and get methods."
So, for the first part, I created one using the following code Java file:
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 finished this and it worked well, but I realized I didn't create any setting methods Can someone explain a better method to me according to the instructions? I'm sure this method works, but I want to do it through this book and understand it better I don't know where to start creating the set method please tell me. Thank you.
PS: it's not a lesson. I just want to understand it better
-Mark
Solution
Simple as:
System.out.println("Enter another price"); double newPrice = keyboard.nextDouble(); obj.setPrice(newPrice);
And print your obj before / after the call (of course: @ overwrite tostring() gets meaningful output on this class)