我试图在默认构造函数中为变量gross赋值,然后让其他方法能够访问它(calc ...方法)。
public class CO2FromWaste
{
CO2FromWaste(int numPeople, boolean paper, boolean plastic, boolean glass, boolean cans)
{
public double ogGrosss = numPeople*1018;
public double grosss = ogGrosss;
if(paper = true)
gross -= 184*numPeople;
if(plastic = true)
gross -= 25.6*numPeople;
if(glass = true)
gross -= 46.6*numPeople;
if(cans = true)
gross -= 165.8*numPeople;
}
private double gross = ogGrosss;
private double ogGross = Grosss;
public void calcGrossWasteEmission()
{
System.out.printf("%20.2f", gross);
}
public void calcWasteReduction()
{
System.out.printf("%20.2f", ogGross - gross);
}
public void calcNetWasteReduction()
{
System.out.printf("%20.2f", gross);
}
}
答案 0 :(得分:1)
你想要的是那些变量是这个类的成员 - 你现在已经将它们声明为构造函数的本地变量。
public class CO2FromWaste
{
// Moved your variables to here, outside of any method.
// They should be declared at/near the top of the class,
// *before* the constructor (by convention)
// I also made them `private` because you don't want code
// that is *outside* of this class to access them.
private double ogGrosss;
private double grosss;
CO2FromWaste(int numPeople, boolean paper, boolean plastic, boolean glass, boolean cans)
{
// Now assign them their values.
// You can optionally use `this`
this.ogGrosss = numPeople*1018;
if(paper == true)
gross -= 184*numPeople;
if(plastic == true)
gross -= 25.6*numPeople;
if(glass == true)
gross -= 46.6*numPeople;
if(cans == true)
gross -= 165.8*numPeople;
}
// removed the declarations from here - these were now duplicates.
public void calcGrossWasteEmission()
{
System.out.printf("%20.2f", gross);
}
public void calcWasteReduction()
{
System.out.printf("%20.2f", ogGross - gross);
}
public void calcNetWasteReduction()
{
System.out.printf("%20.2f", gross);
}
}
请注意=
中的if(paper = true)
运算符是赋值 - 您希望比较这些变量,这是通过{{1}完成的} operator。
(未经测试。我甚至没有尝试编译它,只是修改了你的代码)
另请注意,当您从变量==
中减去浮点值时,它会向下舍入结果。
答案 1 :(得分:0)
我将添加一些提示,以便改进Stephen P的答案。
首先,没有任何理由与布尔值进行比较。您可以简单地写paper == true
而不是paper
。所有if语句都需要一个布尔值。如果该值已经是布尔值,则无需执行比较。因此,通过将if语句更改为:
if(paper)
gross -= 184*numPeople;
if(plastic)
gross -= 25.6*numPeople;
if(glass)
gross -= 46.6*numPeople;
if(cans)
gross -= 165.8*numPeople;
我假设根据您的代码执行的操作,您在构造函数中使用的四个布尔变量中只有一个应该一次为true,其余的应该为false。如果 这种情况,我建议使用枚举来表示选项,否则在错误使用时会使您的类容易受到逻辑错误的影响。您可以将以下文件添加到项目中:
WasteMaterial.java
public enum WasteMaterial {
PAPER, PLASTIC, GLASS, CANS
}
并修改类的构造函数,如下所示:
CO2FromWaste (int numPeople, WasteMaterial material)
{
// Now assign them their values.
// You can optionally use `this`
this.ogGrosss = numPeople*1018;
switch (material) {
case PAPER:
gross -= 184*numPeople;
break;
case PLASTIC:
gross -= 25.6*numPeople;
break;
case GLASS:
gross -= 46.6*numPeople;
break;
case CANS:
gross -= 165.8*numPeople;
break;
}
}
这可以通过将多个值设置为true
来防止类错误地构造( if ,当然,您的规范只允许这四个值中的一个为true
一次)。