【发布时间】:2017-03-31 15:19:02
【问题描述】:
所以我从事这个项目已经有一段时间了,但由于某种原因,我在掌握 Java 方面遇到了很多麻烦。
目标是创建 3 个对象,每个对象包含 3 个水果,每个水果都有自己的价格/价值。
我目前无法将这些值相加,我确信还有很多错误,因为我说到目前为止我在使用 Java 时遇到了很多麻烦。
我目前最大的问题是costofBox()方法。
任何有帮助的建议都将不胜感激,我已经为此工作了一个多星期了。
这是整个程序:
public class Project8
{
private String fruit1;
private String fruit2;
private String fruit3;
private String Bundle1;
private String Bundle2;
private String Bundle3;
private int costofBox;
double total;
int broccoli;
int tomato;
int kiwi;
int kale;
int orange;
public String toString()
{
String output = "The box contains: " + Bundle1 + ", " + Bundle2 + ", " + Bundle3 +
"and the cost is $" + costofBox();
return output;
}
public String getBundle1()
{
return Bundle1;
}
public String getBundle2()
{
return Bundle2;
}
public String getBundle3()
{
return Bundle3;
}
public void setBundle1(String Bundle1)
{
Bundle1=fruit1;
}
public void setBundle2(String Bundle2)
{
Bundle2=fruit2;
}
public void setBundle3(String Bundle3)
{
Bundle3=fruit3;
}
public double costofBox()
{
double total=0;
if(Bundle1.equals("broccoli"))
total+=6;
else if(Bundle1.equals("tomato"))
total+=5;
else if(Bundle1.equals("kiwi"))
total+=8;
else if(Bundle1.equals("kale"))
total+=4;
else if(Bundle1.equals("orange"))
total+=7;
if(Bundle2.equals("broccoli"))
total+=6;
else if(Bundle2.equals("tomato"))
total+=5;
else if(Bundle2.equals("kiwi"))
total+=8;
else if(Bundle2.equals("kale"))
total+=4;
else if(Bundle2.equals("orange"))
total+=7;
if(Bundle3.equals("broccoli"))
total+=6;
else if(Bundle3.equals("tomato"))
total+=5;
else if(Bundle3.equals("kiwi"))
total+=8;
else if(Bundle3.equals("kale"))
total+=4;
else if(Bundle3.equals("orange"))
total+=7;
return total;
}
public Project8()
{
fruit1 = "broccoli" + "kale" + "orange";
fruit2 = "kale" + "kiwi" + "orange";
fruit3 = "broccoli" + "tomato" + "kiwi";
}
public Project8(String fruit1, String fruit2, String fruit3)
{
String Bundle1=fruit1;
String Bundle2=fruit2;
String Bundle3=fruit3;
}
public static void main (String [] args)
{
Project8 Bundle1=new Project8 ("broccoli", "kale", "orange");
Project8 Bundle2=new Project8 ("kale", "kiwi", "orange");
Project8 Bundle3=new Project8 ("broccoli", "tomato", "kiwi");
System.out.println("Week 1: " + Bundle1.toString());
System.out.println("Week 2: " + Bundle2.toString());
System.out.println("Week 3: " + Bundle3.toString());
System.out.println("Week4: The box contains:,, and the cost is $0.0");
}
}
提前感谢那些可以帮助我的人!
【问题讨论】:
-
看起来你最好用
Map<String, Double>来代表每件商品的价格。 -
你应该看看
forloop 和whileloop -
变量,例如
Bundle1,应始终以小写字符开头。没有什么可以强制执行此操作,但它是一种广泛使用的约定,可以使您的代码更易于理解。同样,类应以大写字母开头。 -
您没有正确引用您的值,而不是将您的值存储在变量中,而是将您的值存储在新的字符串值中,这就是您无法访问传递给您的那些值的原因toString() 方法中的对象
-
去看看@Michael的回答
标签: java constructor tostring accessor mutators