尝试在java中编写一个简单的程序,使用else if语句计算运费,我完全迷失了

时间:2017-02-23 05:22:04

标签: java calculator shipping

对于我在我的java课程中的作业,我们应该写一个运费计算器,根据“每运行500英里”每个“重量等级”的“统一费率”来计算最终运费。说明是这样的。

The Fast Freight Shipping Computer charges the following rates:
Weight of Package Rate per 500 Miles Shipped
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80

The shipping charges per 500 miles are not prorated. For example, if a 2 pound
package is shipped 550 miles, the charges would be $2.20. Write a program that asks
the user to enter the weight of a package and the distance traveled, 
and then displays the shipping charges.

我的老师希望我们利用“其他”和“如果”来完成这项任务,但我不介意,如果它是一个小小的鸽友,他实际上是建议使用堆栈溢出来帮助的人,所以我在这里。

基本上我无法弄清楚如何让它每500英里充电 并将其应用到程序中。如果有人可以提供帮助,我会非常感激,并希望了解你是如何理解它的,以及为什么你会这样做。

我很抱歉这个冗长的问题,但我很茫然。香港专业教育学院尝试了多次,并从头开始重新开始,而不是承认这是我最近的尝试:

    public static void main(String[] args) {

    // Declarations

    double finalPrice;
    double shippingRate;
    int milesShipped;
    double packageWeight;
    Scanner keyboard = new Scanner(System.in);

    // Get user input

   System.out.print("Please enter the weight of package in Pounds: ");
    packageWeight = keyboard.nextDouble();

    System.out.print("Please enter the miles traveled in miles: ");
     milesShipped = keyboard.nextInt();

    //Computations

    if (packageWeight <= 2) {
        shippingRate = 1.10;
    }else if (packageWeight >= 2 && packageWeight <= 6)  {
        shippingRate = 2.20;
    }else if (packageWeight >= 6 && packageWeight <= 10)  {
        shippingRate = 3.70;
    }else  {
        shippingRate = 3.80;

    }
    if (milesShipped <= 500)  {
        finalPrice = shippingRate;
    }else if (milesShipped >= 500.0 && milesShipped <= 1000.0) {
        finalPrice = shippingRate;
    }

    ///Display results

    System.out.println("your shipping charges are calculated to be " + '$'+ finalPrice );

1 个答案:

答案 0 :(得分:0)

删除

if (milesShipped <= 500)  {
        finalPrice = shippingRate;//this never updates for each 500 miles
    }else if (milesShipped >= 500.0 && milesShipped <= 1000.0) {
        finalPrice = shippingRate;
    }

将其替换为以下代码

while (milesShipped > 0)  {
        finalPrice += shippingRate;
        milesShipped -= 500;//subtract 500 from the miles till it is less than 0
    }

代码将一直运行直到它小于0,循环的每次迭代都会将运费增加到每个500的最终价格。

让我们说用户为2磅包裹输入1500

first iteration
finalPrice = 1.10
milesShipped-500 = 1000
second iteration
finalPrice = 2.20
milesShipped-500 = 500
third iteration
finalPrice = 3.20
milesShipped-500 = 0

the loop now terminates since milesShipped is no longer greater than 0.