3

This program is meant to act as a shop, with a number being inputted for a corresponding item and a quantity. The catch is that if you want three or more items you receive a 10% discount on the purchase and any decimals should be truncated (staying within whole numbers of the int data type). The program will run, however the discount isn't calculated and is always stated as 0 though the program will run. Check it out!

int item, longsword, shortsword, warhammer, ring, potion, itemcost, quantity, discount, totalcost, finalcost;

    System.out.print("Item Number: ");
    item = keyboard.nextInt();

    final int LONGSWORD = 120;
    final int SHORTSWORD = 90;
    final int WARHAMMER = 80;
    final int RING = 150;
    final int POTION = 10;

    itemcost = 0;

    if (item == 1)
    {
        itemcost = LONGSWORD;
    }

    if (item == 2)
    {
        itemcost = SHORTSWORD;
    }   

    if (item == 3)
    {
        itemcost = WARHAMMER;
    }   

    if (item == 4)
    {
        itemcost = RING;
    }

    if (item == 5)
    {
        itemcost = POTION;
    }

    System.out.print("Quantity of Item: ");
    quantity = keyboard.nextInt();  

    totalcost = itemcost * quantity;

    System.out.println("Total Cost: " + totalcost);

    if (quantity >= 3)
    {
        discount = totalcost * (1/10);
    }

    else
    {
        discount = 0;
    }

    System.out.println("Discount: " + discount);
katef
  • 31
  • 4

2 Answers2

8

You are experiencing the oh-so-common integer division issue.

discount = totalcost * (1/10);

1/10 is 0, so discount will be 0. Use this instead:

discount = (int) (totalcost * (0.1));
pathfinderelite
  • 3,047
  • 1
  • 27
  • 30
3

You need to try

discount = totalcost * (0.1);

instead of

discount = totalcost * (1/10);

As 1/10 will result in 0(integer division) or else change it like

discount = totalcost * (1/10.0);

Also I would suggest you to change the type of discount to double instead of int else you need to cast it like this:

discount = (int) (totalcost * (0.1));

The reason why I am saying to change the type to double is because the discount could be in decimals also so it would be better to store it in double instead casting it to int.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331