0
import java.util.*;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter price: $");
float price = keyboard.nextFloat();
System.out.println("Early payment (Y/N): ");
String char1 = keyboard.nextLine();

float amount = price;

if (char1.equals('Y'))
{
  amount = price * 0.9;
}

System.out.printf("Amount due: $%0.2f\n", amount);


}
}

when compiling it gives the error of possible lossy conversion, regardless if i pass an int or float.. what is the issue here?

Rino
  • 81
  • 6

2 Answers2

1

In Java by default every decimal number is considered double. You are multiplying a float by double which result in a double:

float price = 10.7f;
float result = price * 0.9; //this does not work

Here, we have two options. The first one is to convert 0.9 as float, putting the f in the front of the number:

float result = price * 0.9f;

The second option is to hold the result as double:

double result = price * 0.9;

Please, use double/float only for doing simple tests. Here we have a good explanation about the difference between Double and BigDecimal:

vallim
  • 308
  • 2
  • 12
0

The main issue is that 0.9 is a double, which causes the value of price * 0.9 to be coerced to a double as well. To prevent that, you should use 0.9f to indicate you want a float type.

You also have an issue with char1 actually being a String, not a char, so char1.equals('Y') will always be false.

In addition, your %0.2f format says you want to zero-fill your output, but you neglected to specify a minimum width. Something like %04.2f should work.

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter price: $");
        float price = keyboard.nextFloat();
        System.out.println("Early payment (Y/N): ");
        String str1 = keyboard.next();

        float amount = price;

        if (str1.equals("Y")) {
          amount = price * 0.9f;
        }

        System.out.printf("Amount due: $%04.2f\n", amount);
    }
}
cybersam
  • 63,203
  • 6
  • 53
  • 76