我是Java的新手,我的编译器没有告诉我此代码的错误:
public class Main {
public static void main(String args[]) {
class gasStation {
double price;
double distance;
}
gasStation shell = new gasStation();
shell.price = 2.72;
shell.distance = 1.25;
gasStation exxon = new gasStation();
exxon.price = 2.35;
exxon.distance = 1.75;
class betterDeal {
public gasStation compare(gasStation shell, gasStation exxon) {
double shellRating = shell.price * shell.distance;
double exxonRating = exxon.price * exxon.distance;
if (shellRating > exxonRating) {
gasStation better = shell;
} else if (shellRating < exxonRating) {
gasStation better = exxon;
}
return better;
}
System.out.println (better);
}
}
}
答案 0 :(得分:1)
您的代码中有几个错误。
在better
范围之外初始化变量if
。
gasStation better = null;
if (shellRating > exxonRating) {
better = shell;
} else if (shellRating < exxonRating) {
better = exxon;
}
return better;
所有语句应位于方法内部或块内。将您的System.out.println(better);
语句放在compare
方法中,在return语句之前。
public gasStation compare(gasStation shell, gasStation exxon) {
double shellRating = shell.price * shell.distance;
double exxonRating = exxon.price * exxon.distance;
gasStation better = null;
if (shellRating > exxonRating) {
better = shell;
} else if (shellRating < exxonRating) {
better = exxon;
}
System.out.println(better);
return better;
}
您可以从gasStation
类中退出betterDeal
类和Main
类。
为什么我不能在代码末尾打印“更好”的对象?这是因为您从未调用过compare
方法。创建betterDeal
类的新对象,并在compare
方法内调用main
方法以打印变量better
。
new betterDeal().compare(shell, exxon);
但是,仍然需要打印price
变量的distance
和better
时,您必须覆盖{ {1}}类。
toString()
完整代码:
gasStation