gpt4 book ai didi

java - 重量转换程序出现问题

转载 作者:行者123 更新时间:2023-12-01 16:00:43 26 4
gpt4 key购买 nike

import java.util.Scanner;
import java.text.DecimalFormat;


public class WeightConverter
{
private double numOfLbs2Conv, numOfKilos2Conv, converted2Pounds, converted2Kilograms;
private final double WEIGHT_CONVERSION_FACTOR = 2.20462262;
private int desiredDecimalPlaces;
private boolean toKilos, toPounds;

public void readPoundsAndConvert()
{
toKilos = true;
System.out.print("Enter the number of pounds to convert to "
+ "kilograms: ");
Scanner keyboard = new Scanner(System.in);
numOfLbs2Conv = keyboard.nextDouble();
converted2Pounds = numOfLbs2Conv / WEIGHT_CONVERSION_FACTOR;
}


public void readKilogramsAndConvert()
{
toPounds = true;
System.out.print("Enter the number of kilograms to convert to "
+ "pounds: ");
Scanner keyboard = new Scanner(System.in);
numOfKilos2Conv = keyboard.nextDouble();
converted2Kilograms = numOfKilos2Conv * WEIGHT_CONVERSION_FACTOR;
}


public void displayBothValues()
{
System.out.print("How many places after the decimal would you like? ");
Scanner keyboard = new Scanner(System.in);
desiredDecimalPlaces = keyboard.nextInt();

String decimalCounter = "0.";
for (int i = 0; i < desiredDecimalPlaces; i++)
{
decimalCounter = decimalCounter + "0";
}

DecimalFormat decimalsConverted = new DecimalFormat(decimalCounter);


if (toKilos)
{

System.out.println("The number of kilograms in "
+ decimalsConverted.format(numOfLbs2Conv) + " pounds is "
+ decimalsConverted.format(converted2Kilograms) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}


if (toPounds)
{

System.out.println("The number of pounds in "
+ decimalsConverted.format(numOfKilos2Conv) + " kilograms is "
+ decimalsConverted.format(converted2Pounds) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
}
}

大家好。我在整理这些内容时遇到了困难。输出端已拧紧。如果用户首先转换为磅 (readPoundsAndConvert()),则输出会显示转换后的答案为 0。如果用户首先转换千克,则千克将正确转换,然后出于某种原因 readPoundsAndConvert() 方法将被调用并且行为正常。我不知道为什么会发生这种情况,并且已经花了几个小时在这上面。有人可以告诉我如何让它正常工作吗?如果您需要我发布程序的其余部分,我会的。

最佳答案

您正在向后使用变量...在readPoundsAndConvert()中,您将转换后的值存储在converted2Pounds中,但是当您尝试显示它时,您正在从converted2Kilograms中读取。

关于java - 重量转换程序出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010790/

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