我尝试更改coupe
的值,但输出不会更改。在NetBeans中,我将这两个程序保存在同一个项目和包中。我没有在这里包含它,因为它可能使代码太长了,但我也写了可以正常工作的accessor方法,所以我很困惑为什么mutator方法不起作用。Mutator方法不起作用,NetBeans
类代码:
package auto;
public class Auto
{
private String model;
private int milesDriven;
private double gallonsOfGas;
public Auto(String startModel,
int startMilesDriven,
double startGallonsOfGas)
{
model = startModel;
setMilesDriven(startMilesDriven);
setGallonsOfGas(startGallonsOfGas);
}
public void setModel(String newModel)
{
model = newModel;
}
public void setMilesDriven(int newMilesDriven)
{
if (newMilesDriven >= 0)
milesDriven = newMilesDriven;
else
{
System.err.println("Miles driven cannot be negative.");
System.err.println("Value not changed.");
}
}
public void setGallonsOfGas(double newGallonsOfGas)
{
if (newGallonsOfGas >= 0.0)
gallonsOfGas = newGallonsOfGas;
else
{
System.err.println("Gallons of gas cannot be negative.");
System.err.println("Value not changed.");
}
}
}
客户端类代码:
package auto;
import java.text.DecimalFormat;
public class AutoClient
{
public static void main(String [] args)
{
DecimalFormat milesPattern = new DecimalFormat("#,###");
Auto coupe = new Auto("Corvette", 300000, 0.0);
String coupeModel = coupe.getModel();
int coupeMiles = coupe.getMilesDriven();
double coupeGallons = coupe.getGallonsOfGas();
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
}
}
你能解释为什么你认为Netbeans与这个问题有关吗? –
最初,我认为这是我保存文件的一个问题(例如,它们是否在同一个软件包中)。我是IDE和编程新手。 – pez
够公平的。但是,如果这是问题所在,则会出现编译错误,而不是运行的程序,但会给出错误答案。 –