gpt4 book ai didi

Java MPG 计算器

转载 作者:行者123 更新时间:2023-11-30 03:44:40 25 4
gpt4 key购买 nike

我已经完成了简单 MPG 的大部分代码计算器。我现在的主要问题是在程序结束时我需要它来计算用户决定输入的所有里程的平均 MPG。

我得到了一些数字,但它不是正确的。如果你能向我请求你的知识,那就太棒了。如果还有其他问题,请告诉我,我会接受任何批评。

import java.util.Scanner;

public class GasMileage {

public static void main(String[] args) {
GasMileage mileage1 = new GasMileage();
GasMileage mileage2 = new GasMileage();

Scanner input = new Scanner(System.in);

System.out.println("Welcome to the MPG calculator!");
double counterM;
double counterG;
double mileage;
double gallons;
double mpg;
double average;

String repeat = "yes";

while (repeat.equals("Yes") ||
repeat.equals("yes") ||
repeat.equals("y") ||
repeat.equals("Y")) {

System.out.println("Enter miles driven: ");
mileage = input.nextDouble();
counterM = mileage++;
mileage1.setMilesDriven(mileage);
mileage2.setMilesDriven(counterM);

System.out.println("Enter gallons used: ");
gallons = input.nextDouble();
counterG = gallons++;
mileage1.setGallonsUsed(gallons);
mileage2.setGallonsUsed(counterG);

mileage1.setMpg(mileage, gallons);
mileage2.setMpg(counterM, counterG);
mpg = mileage1.getMpg();
System.out.println("Your mpg is: " + mpg);

System.out.println("repeat? ");
repeat=input.next();
}

average = mileage2.getMpg();
System.out.println("Your total average mpg is: " + average);
}

double milesDriven;
double gallonsUsed;
double mpg1;

public void setMilesDriven(double Miles) {
milesDriven = milesDriven + Miles;
}
public void setGallonsUsed(double Gallons) {
gallonsUsed = gallonsUsed+Gallons;
}

public double getMilesDriven() {
return milesDriven;
}

public double getGallonsUSed() {
return gallonsUsed;
}

public void setMpg(double setM, double setG) {
mpg1 = (setM) / setG;
}

public double getMpg() {
return mpg1;
}
}

最佳答案

mileage++实际上会增加里程的值(value)。

int mileage = 1;
int gallons = mileage++; // mileage will equal 2 after this

顺便说一句,永远不要等到最后才清理/格式化你的代码。干净的代码将更容易阅读,因此更容易发现问题。

关于Java MPG 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com