gpt4 book ai didi

java - 学习构造函数和对象

转载 作者:行者123 更新时间:2023-12-01 21:14:27 25 4
gpt4 key购买 nike

我刚刚对构造函数和对象进行了一次测验(幸运的是没有测试),结果相对较差。

我以为我已经弄清楚了,但我就是没有。

我们收到的问题基本上是制作一个子三明治模拟器。我们刚刚被告知它有“面包”“蔬菜数量”和“肉类类型”

这里的问题确实是我不理解这一点,而不是我没有阅读过无数相关内容。所以我想看看这里是否有人能以我能理解的方式向我解释这一点。对于我们想要做的事情来说,似乎有太多的方法。

这就是我的进展:

   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方法。

我主要好奇的是修改方法以及我到底如何访问它们并使用它们?

最佳答案

你的构造函数非常好。它将这些私有(private)变量设置在类的顶部。

public class SubSandwich{
private String bread;
private int numVegs;
private String meat;

// Constructor
public SubSandwich(String b, int nv, String m){
bread = b;
numVegs = nv;
meat = m;
}

现在,您不了解 setter 吗?尝试用 setBread(b) 替换构造函数 bread = b。换句话说,setter 方法或多或少是构造函数完成的操作的子集。 它设定了值,这并不复杂。

现在,这并不完全是对现实世界三明治的建模,但如果您想将面包换成一种特定的三明治

SubSandwich blah = new SubSandwich("White", 2, "Chicken");
printSandwich(blah); // prints white
blah.setBread("wheat");
printSandwich(blah); // prints wheat

您需要实现您的方法来反射(reflect)该更新

您还可以实现 toString 方法,这样您就可以简单地执行

System.out.println(blah);

关于java - 学习构造函数和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com