我正在做一个简单的 Java 作业。看来我的语法和逻辑都是正确的。但是,构造函数无法理解我尝试传入的参数,这就是为什么所有计算都是错误的。我已附上输出。有人知道如何解决这个问题吗?任何帮助将不胜感激。谢谢!
public class DT_CarStats
{
private double gallons;
private double mpg;
private double ppg;
public DT_CarStats(double gallons, double mpg, double ppg)
{
gallons = gallons;
mpg = mpg;
ppg = ppg;
}
public double CostPer100()
{
return 100 / (mpg * ppg);
}
public double MaxDistance()
{
return mpg * gallons;
}
}
import java.util.Scanner;
public class DT_CarStatsTester
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
double gallons, mpg, ppg;
System.out.printf("******************************************* \n");
System.out.printf("* Welcome to my Distance to Empty App * \n");
System.out.printf("******************************************* \n");
System.out.printf("Please enter the number of gallons of gas in the tank: ");
gallons = scannerObject.nextDouble();
System.out.printf("Please enter the fuel efficiency (miles per gallon): ");
mpg = scannerObject.nextDouble();
System.out.printf("Please enter the price of gas per gallon: ");
ppg = scannerObject.nextDouble();
DT_CarStats cs = new DT_CarStats(gallons,mpg,ppg);
System.out.printf("\n");
System.out.printf("To drive 100 miles, it will cost $" + cs.CostPer100() + ". \n");
System.out.printf("The car can currently drive a maximum of " + cs.MaxDistance() + " miles. \n");
System.out.printf("******************************************* \n");
System.out.printf("* Thanks for using our App, Safe Travels! * \n");
System.out.printf("******************************************* \n");
}
}
示例运行:
*******************************************
*******************************************
* Welcome to my Distance to Empty App *
*******************************************
Please enter the number of gallons of gas in the tank: 17.6
Please enter the fuel efficiency (miles per gallon): 24.8
Please enter the price of gas per gallon: 2.36
To drive 100 miles, it will cost $Infinity. ==> This is wrong, should be $9.52
The car can currently drive a maximum of 0.0 miles. ==> This should be 436.48 miles
*******************************************
* Thanks for using our App, Safe Travels! *
*******************************************
最佳答案
使用 this
指定您指的是类字段,而不是构造函数参数,因为它们的名称相同。
public DT_CarStats(double gallons, double mpg, double ppg)
{
this.gallons = gallons;
this.mpg = mpg;
this.ppg = ppg;
}
关于java - 如何在构造函数中传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28652430/