为什么我无法更好地获得加油站的结果?

时间:2018-11-11 04:05:04

标签: java

我是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);
        }
    }

}

1 个答案:

答案 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变量的distancebetter时,您必须覆盖{ {1}}类。

    toString()

完整代码:

gasStation