'Java JDK - possible lossy conversion from double to int

So I have recently written the following code:

    import java.util.Scanner;

public class TrainTicket
{
      public static void main (String args[])
      {
     
         Scanner money = new Scanner(System.in);
         System.out.print("Please type in the type of ticket you would like to buy.\nA. Child B. Adult C. Elder.");
         String type = money.next();
         System.out.print("Now please type in the amount of tickets you would like to buy.");
         int much = money.nextInt();
         int price = 0;
         switch (type)
          {
            case "A":
            price = 10;
            break;
            case "B":
            price = 60;
            break;
            case "C":
            price = 35;
            break;
            default:
            price = 0;
            System.out.print("Not a option ;-;");
           }
          if (price!=0)
          {
            int total2 = price* much* 0.7;
            System.out.print("Do you have a coupon code? Enter Y or N");
            String YN = money.next();
            if (YN.equals("Y"))
            {
             System.out.print("Please enter your coupon code.");
             int coupon = money.nextInt();
             if(coupon==21)
             {
              System.out.println("Your total price is " + "$" + total2 + ".");
             }
             else
             {
              System.out.println("Invalid coupon code, your total price is " + "$" + price* much + ".");
             }
            }
            else
            {
            System.out.println("Your total price is " + "$" + price* much + "." ); 
            }
          }
        
       money.close();
      }
}

When I try and run it with cmd, it keeps displaying this:

TrainTicket.java:31: error: incompatible types: possible lossy conversion from double to int
            int total2 = price* much* 0.7;

Can someone help and explain the error that I have made?



Solution 1:[1]

You are trying to assign price* much* 0.7, which is a floating point value (a double), to an integer variable. A double is not an exact integer, so in general an int variable cannot hold a double value.

For instance, suppose the result of your calculation is 12.6. You can't hold 12.6 in an integer variable, but you could cast away the fraction and just store 12.

If you are not worried about the fraction you will lose, cast your number to an int like this:

int total2 = (int) (price* much* 0.7);

Or you could round it to the nearest integer.

int total2 = (int) Math.round(price*much*0.7);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1