gpt4 book ai didi

java - 重量转换 - 如何将各种打印方法组合成一种打印方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:07:38 24 4
gpt4 key购买 nike

我是一名正在学习 Java 的新手程序员,虽然我的作业已经完成,但我想让它更整洁。我想知道我是否可以将以下打印方法合并为一个,并且至少将公斤到磅和磅到公斤的方法合并为一个。

请注意,我不能使用比 if 语句和循环更高级的东西。

因为这是我第一次发帖,我想确保我为所有回答者提供了足够的信息我已经将我的体重转换 java 文件上传到这里:Weight Conversion Java file .

关于如何简化代码或遵循更好的代码礼仪的任何其他建议也受到欢迎。

打印语句如下:

/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS1( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print(dResult1 + " pounds is " + dResult2 + " kilograms.");
}// end method printRESULTS1

/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS2( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print( dResult1 + " kilograms is " + dResult2 + " pounds");
}// end method printRESULTS2

/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS3( double dResultOZ, double dResultLBS){
// Prints the result of Pounds to Kilograms
System.out.print( dResultOZ + " ounces is " + dResultLBS + " pounds");
}// end method printRESULTS3

/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS4( double dResultLBS, double dResultOZ){
// Prints the result of Pounds to Kilograms
System.out.print( dResultLBS + " pounds is " + dResultOZ + " ounces ");
}// end method printRESULTS4

最佳答案

首先,考虑一下:

public static void printResults(
double dResultFrom,
String from,
double dResultTo,
String to)
{
System.out.print(dResultFrom + " " + from + " is " + dResultTo + " " + to);
}

不确定您正在使用它的整个上下文以及您的局限性。当然,进一步的重构步骤是可能的。例如:

public static void printResults(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
String formattedResult = formatResult(
resultFrom,
fromDescription,
resultTo,
toDescription);

System.out.print(formattedResult);
}

public static String formatResult(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
return formatQuantity(resultFrom, fromDescription)
+ " is "
+ formatQuantity(resultTo, toDescription);
}

public static String formatQuantity(double value, String description)
{
return value + " " + description;
}

请注意,与您的示例相比,代码重复要少得多,并且职责明确分离(格式化功能和打印功能)。例如,如果您必须将结果打印到文件中,而不是打印到控制台,那么这种设计会更加灵活。

关于java - 重量转换 - 如何将各种打印方法组合成一种打印方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214409/

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