java 第 16 课 - 油耗 - 多类项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7544031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:25:01  来源:igfitidea点击:

Lesson 16 - Gas Mileage - Multiple Classes Project

java

提问by Alex G

~~~Update: Solved! Thanks everyone!~~~

I'm working on a project from the Blue Pelican Java book, lesson 16 project Gas Mileage. It asks to create two classes, one is Automobile which holds the methods I will work with. The other class, Tester, is the main class. Every time I run the Tester class, it returns a value of -Infinity. I can't figure out why, other than that I've singled out the problem is in the Automobile class at line 14 in the takeTrip method. When I leave that method out of the Tester class, it returns the correct values. This is the Automobile class:

~~~更新:解决了!谢谢大家!~~~

我正在处理 Blue Pelican Java 书籍第 16 课项目 Gas Mileage 中的一个项目。它要求创建两个类,一个是汽车,它包含我将使用的方法。另一个类 Tester 是主类。每次我运行 Tester 类时,它都会返回一个值 -Infinity。我不知道为什么,除了我在 takeTrip 方法的第 14 行中指出问题出在汽车类中。当我将该方法排除在 Tester 类之外时,它会返回正确的值。这是汽车类:

public class Automobile
{
    public Automobile(double m) // Accepts value m to the double mpg. Also declares
    {
        double mpg = m;
        double gallons;
    }
    public void fillUp(double f) // Adds fuel to the tank
    {
        gallons += f;
    }
    public void takeTrip(double t) // Takes away fuel from the tank depending upon how many miles are driven
    {
        gallons -= t / mpg; // Not sure how to do this line. For some reason, when I reference mpg, the output of Tester is "-infinity". Shouldn't it do gallons = gallons - (miles driven / mpg)?
    }
    public double reportFuel() // Returns value of how much fuel is left in tank
    {
        double r = gallons;
        return r;
    }
    public double mpg;
    public double gallons;
}


And this is the Tester class:


这是 Tester 类:

public class Tester
{
    public static void main(String args[])
    {
        Automobile myBmw = new Automobile(24); // Passes constructor argument of 24 mpg
        myBmw.fillUp(20); // Adds 20 gallons to fillUp method
        myBmw.takeTrip(100); // Takes away the fuel used for 100 miles using the takeTrip method
        double fuel_left = myBmw.reportFuel(); // Initializes fuel_left to the method reportFuel
        System.out.println(fuel_left);
    }
}

Any help is appreciated, thanks! -AJ

任何帮助表示赞赏,谢谢!-AJ

回答by Cory Kendall

You constructor doesn't need the 'double' identifier. Here you are creating a newvariable alsocalled mpg, which is forgotten after the constructor completes. Instead use this:

您的构造函数不需要“双”标识符。在这里,您正在创建一个变量,称为 mpg,它在构造函数完成后被遗忘。而是使用这个:

public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
    mpg = m;
}

回答by Jon Skeet

This is the problem:

这就是问题:

public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
    double mpg = m;
    double gallons;
}

This is declaring a localvariable called mpg, rather than changing the value of the instancevariable for the object. (The instance variables are declared at the bottom of the class.) It's then declaring another local variable called gallonswhich isn't assigned any value. At the end of the constructor, the instance variables gallonsand mpgwill both be zero - which means you'll be dividing by zero in the takeTripmethod - so you're subtracting "infinity gallons" from the fuel tank, leading to your final result. Your constructor should look like this instead:

这是声明一个名为的局部变量mpg,而不是更改对象的实例变量的值。(实例变量在类的底部声明。)然后声明另一个gallons未分配任何值的局部变量。在构造函数的末尾,实例变量gallonsmpg都将为零 - 这意味着您将在该takeTrip方法中除以零- 所以您从油箱中减去“无穷大加仑”,从而得出最终结果。你的构造函数应该看起来像这样:

public Automobile(double m)
{
    this.mpg = m;
}

or just:

要不就:

public Automobile(double m)
{
    mpg = m;
}

If you're still unsure about local variables and instance variables after this, see if there's anything earlier in the book which might help you. (By lesson 16 I'd expectit to have been covered...)

如果您在此之后仍然不确定局部变量和实例变量,请查看本书前面的任何内容可能对您有所帮助。(到第 16 课时,我希望它已被涵盖...)

回答by Eran Zimmerman

In your Automobilec'tor, you're currently creating a localvariable called mpg, instead of changing the class member. All there should be in that function is mpg = m;(the second line does nothing).

在您的Automobilec'tor 中,您当前正在创建一个名为 mpg的局部变量,而不是更改类成员。该函数中应该有的只是mpg = m;(第二行什么都不做)。

Currently, mpg (the member) is automatically initialized to 0, and then t/mpg is infinity, and when you take that away from some finite number, you get -infinity.

目前,mpg(成员)被自动初始化为 0,然后 t/mpg 是无穷大,当你把它从某个有限数中取出时,你会得到 -infinity。

By the way, in reportFuel(), you could just as well just write return gallons;, without declaring r.

顺便说一句,在 中reportFuel(),您也可以直接编写return gallons;,而无需声明r.

回答by Alim Ul Gias

Why are again declaring your attributes inside your constructor where as you have already declared them in your class. Actually the attributes you are declaring inside the constructor will not persist after the execution of the method ends (in this case the constructor). So though you are trying to initialize the attributes of your class you are actually not doing this.

为什么要在构造函数中再次声明属性,因为您已经在类中声明了它们。实际上,您在构造函数中声明的属性在方法执行结束后(在本例中为构造函数)不会持续存在。因此,尽管您尝试初始化类的属性,但实际上并没有这样做。

So in your constructor try this

所以在你的构造函数中试试这个

mpg=m
gallons=0

I think the other methods are fine. Another thing try to keep those attributes (mpg and gallons) private. Though the program will run without any error still you are violating the main thing of oop - encapsulation. cheers :)

我认为其他方法都很好。另一件事是尝试将这些属性(mpg 和加仑)保密。尽管该程序将运行而不会出现任何错误,但您仍然违反了 oop 的主要内容 - 封装。欢呼:)

回答by user710502

public class Automobile {    

    private double mpg = 0; //need to handle the division by 0 if you
                            //initialize it to 0
    private double gallons = 0;

    public Automobile(double m, double g)      
            {        
                 mpg = m;         
                 gallons = g;
             }