重量转换程序有问题

时间:2010-10-24 22:22:41

标签: java

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()方法将被称为行为正常。我不知道为什么会发生这种情况并花费数小时才能完成。有人能告诉我如何让这个行为正常吗?如果你需要我发布剩下的程序,我会。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您似乎在两个“转化”方法中将toKilostoPounds设置为true,但您没有同时将另一个设置为false 。因此,如果您之前调用了其中一种转化方法,那么当您致电displayBothValues()时,toKilostoPoundstrue,并且两者都将被打印。

相关问题