Java, subject mathematics

This program is designed to operate as a store, with a number entered for the corresponding item and quantity. The trick is that if you want three or more items, you get a 10% discount on your purchase, and any decimals must be truncated (staying within the int). The program will work, however the discount is not calculated and is always indicated as 0 , although the program will work. Check it!

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);

      

+3


source to share


2 answers


You have a problem with generic integer separation.

discount = totalcost * (1/10);

      



1/10

is 0, so it discount

will be 0. Use this instead:

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

      

+8


source


You need to try

discount = totalcost * (0.1);

      

instead

discount = totalcost * (1/10);

      

Since 1/10 will result in 0 (integer division) or change it to be



discount = totalcost * (1/10.0);

      

Also I suggest you change the type discount

to double

instead of int

else, which you need to do like this:

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

      

The reason I say to change the type to double is because the discount might be in decimals

, so it would be better to keep it in double

instead of discarding it to int

.

+3


source