【发布时间】:2017-03-24 00:00:39
【问题描述】:
我刚刚对相对较差的构造函数和对象进行了测验(幸运的是没有测试)。
我以为我已经弄清楚了,但我没有。
我们收到的问题基本上是制作一个子三明治模拟器。我们刚刚被告知它有“面包”“蔬菜数量”和“肉类类型”
这里的问题确实是我不明白这一点,而不是我没有读过无数关于它的内容。所以我想看看这里是否有人能以我能理解的方式向我解释这一点。似乎有太多方法可以用于我们尝试为一个人做的事情。
这是我做到了多少:
import java.util.Scanner;
public class SubSandwich{
Scanner in = new Scanner(System.in);
private String bread;
private int numVegs;
private String meat;
// Constructor
public SubSandwich(String b, int nv, String m){
bread = b;
numVegs = nv;
meat = m;
}
// Get the value of bread
public String getBread(){
return bread;
}
// Get the value of numVegs
public int getNumVegs(){
return numVegs;
}
// Get the value of meat
public String getMeat(){
return meat;
}
// Modify the value of bread
public void setBread(String b){
}
// Modify the value of numVegs
public void setNumVegs(int nv){
}
// Modify the value of meat
public void setMeat(String m){
}
// Calculate and return the total cost of a sub sandwich.
// The total cost is $5.00,
// plus $0.50 for each vegetable.
public double getTotalCost(){
double totalCost = 5.00 + (getNumVegs() * .50);
return totalCost;
}
public String toString(){
System.out.println("You have a ");
}
public static void main(String[]args){
SubSandwich sandwich1 = new SubSandwich("White", 2, "Chicken");
}
public static void printSandwich(SubSandwich sandwich1){
System.out.println("The sandwich you ordered is " + sandwich1.getBread() + " and " + sandwich1.getNumVegs() + " vegetables, and " + sandwich1.getMeat() + ".\n That comes to $" + sandwich1.getTotalCost() + "." );
}
}
我想知道“修改”方法的具体用途是什么?我应该如何使用它们?
如果这看起来非常模糊,我很抱歉,我想是的,也许我还不够理解。这是给我们的模板,但我填写了一些我认为我理解的东西。我试过在main方法中提问和取数据,但是无法使用非静态方法返回main方法。
我对它的修改方法以及我如何访问它们感到好奇的主要是使用它们?
【问题讨论】:
标签: java object constructor