[英]Paint conversion (JAVA NETBEANS)
我正在尝试做一个油漆转换项目。 最终我会制作一个 GUI,但我想先充实它。 我在下面有代码。 有没有人可以简化这一点,而不仅仅是拥有一堆不同的方法? 下面将主要介绍 class 和方法 class ,它显示了我如何计算所有内容。 原谅我第一次在这里发布问题的任何乱七八糟的格式。
package paintconversion;
/** @author JoshS */
public class Paint2Quart {
private double Quart;
private double Gallon;
private double Pint;
public Paint2Quart() {
Quart = 0;
Gallon = 0;
Pint = 0;
}
// Method to convert Quart to Gallon
public void setQuartToGallon(double conQuart) {
if (conQuart > 0) {
Quart = conQuart / 4;
System.out.println(conQuart + " quart equals " + Quart + " Gallon(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
// Method to convert Gallon To Quart
public void setGallonToQuart(double conGallon) {
if (conGallon > 0) {
Gallon = conGallon * 4;
System.out.println(conGallon + " gallon equals " + Gallon + " Quart(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
public void setPintToGallon(double conPint) {
if (conPint > 0) {
Pint = conPint / 8;
System.out.println(conPint + " pint equals " + Pint + " Gallon(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
public void setPintToQuart(double conPint) {
if (conPint > 0) {
Pint = conPint / 2;
System.out.println(conPint + " pint equals " + Pint + " Quart(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
public void setGallonToPint(double conGallon) {
if (conGallon > 0) {
Gallon = conGallon * 8;
System.out.println(conGallon + " Gallon equals " + Gallon + " Pint(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
public void setQuartToPint(double conQuart) {
if (conQuart > 0) {
Pint = conQuart * (2);
System.out.println(conQuart + " Quart equals " + Pint + " Pint(s)");
} else {
System.out.println("Numbers Must Be Positive!");
}
}
}
我会将所有数量转换为幕后的通用单位,然后根据需要将它们转换回来。 比如说,在一个名为 Volume 的 class 中:
public class Volume {
private double gallons;
private Volume(double gallons) {
if (gallons < 0) {
throw new IllegalArgumentException("value must be positive");
}
this.gallons = gallons;
}
public static Volume ofGallons(double gallons) {
return new Volume(gallons);
}
public static Volume ofQuarts(double quarts) {
return new Volume(quarts / 4);
}
public static Volume ofPints(double pints) {
return new Volume(pints / 8);
}
public static Volume ofLiters(double liters) {
return new Volume(0.264172 * liters);
}
public double asGallons() {
return gallons;
}
public double asQuarts() {
return gallons * 4;
}
public double asPints() {
return gallons * 8;
}
public double asLiters() {
return gallons / 0.264172;
}
@Override
public String toString() {
return gallons + " gallon" + (gallons == 1 ? "" : "s");
}
}
然后,要将体积从品脱转换为夸脱:
quarts = Volume.ofPints(pints).asQuarts();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.