Possible lossy conversion while compiling in Java [duplicate] - java

This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
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?

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:

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

Related

How to raise a double to a power

Cannot figure out how to raise the formula to a power. I have imported the java.lang.Math in java also. I just keep getting the Sytax error on "Math" delete this token and cannot invoke pow(double) on the primitive data type double errors
This is the formula assuming a 30 year loan
Annuity Factor = (0.003125*(1+0.003125)^360)/(((1+0.003125)^360)-1)
the 360 is 30 years time 12 months to get the monthly payment
import java.util.Scanner;
import java.lang.Math;
public class HW3Method {
public static void main(String[] args) {
// main method for user inputs
Scanner info = new Scanner(System.in);
System.out.println("Enter the starting annual rate as a percent (n.nnn)");
double startRate = info.nextDouble();
System.out.println("Enter the ending annual rate as a percent (n.nnn)");
double endRate = info.nextDouble();
System.out.println("Enter the annual intrest rate increments as a percent (n.nnn)");
double rateIncrease = info.nextDouble();
System.out.println("Enter the first term in years for calculating payments");
double firstTerm = info.nextDouble();
System.out.println("Enter the last term in years for calculating payments");
double lastTerm = info.nextDouble();
System.out.println("Enter the term increment in years");
int termIncrement = info.nextInt();
System.out.println("Enter the loan amount");
double loanAmount = info.nextDouble();
double mtp = firstTerm * 12;
}
public double calcAnnuity(double mtp ) {
double annuityFactor = (0.003125*(1+0.003125)Math.pow(mtp));
return annuityFactor;
}
}
Explanation
You are using the method Math.pow wrong. It wants two arguments, the base and the exponent. You wrote:
0.003125 * (1 + 0.003125) Math.pow(mtp)
But you need to write:
0.003125 * Math.pow(1.0 + 0.003125, mtp)
Notes
Note that 1.0 + 0.003125 can be simplified to just 1.003125, so:
0.003125 * Math.pow(1.003125, mtp)
Even better would be to store that magical number somewhere as constant, then you only need to change one variable and not many:
private static final int FACTOR = 0.003125;
And then use that constant:
FACTOR * Math.pow(1.0 + FACTOR, mtp)
Documentation
From the official documentation of Math.pow:
public static double pow​(double a, double b)
Returns the value of the first argument raised to the power of the second argument. Special cases: [...]

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?
When you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.
In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.
So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:
int total2= (int) price*much*0.7;
/*(int) tells compiler that you are aware of what you are doing.*/
//also called as type casting
In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.
double total2=price*much*0.7;
float total2=price*much*0.7;
//will work
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);

How do I invoke a class from my Main method in Java?

I'm trying to have a user input a couple of numbers and I show the output using newNumerator = in.nextDouble(); but I'm asked to change Fraction newNumerator to a double and if I do, I than have to change it to Fraction.
What am I missing?
import java.util.Scanner;
public class FractionTest {
public static void main(String[] args){
Fraction newNumerator;
Fraction newDenominator;
newNumerator = new Fraction();
newDenominator = new Fraction();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a numerator: ");
newNumerator = in.nextDouble(); // I get an error here
System.out.println("Please enter a denominator: ");
newDenominator = in.nextDouble(); // I get an error here
in.close();
}
}
The above is my Main() and the following is my class.
public class Fraction {
public double numeratorAnswer;
public double denominatorAnswer;
public Fraction() {
}
public double getNumeratorAnswer(){
return numeratorAnswer;
}
public void setNumeratorAnswer(double newNumerator){
numeratorAnswer = newNumerator;
}
public double getDenominatorAnswer(){
return denominatorAnswer;
}
public void setDenominatorAnswer(double newDenominator){
denominatorAnswer = newDenominator;
}
}
You are trying to put a double into a Fraction variable instead of putting the double in the Fraction.
To fix this, use a single Fraction value and call setNumeratorAnswer and setDenominatorAnswer with your in.nextDouble().
You are trying to assign a double value to an object of Fraction class in following statements:
newNumerator = in.nextDouble(); // I get an error here
System.out.println("Please enter a denominator: ");
newDenominator = in.nextDouble(); // I get an error here
As this cast is not possible so you need to take the double inputs and then assign Fraction class numeratorAnswer and denominatorAnswer attributes. Something like this:
double dnewNumerator = in.nextDouble();
System.out.println("Please enter a denominator: ");
double dnewDenominator = in.nextDouble();
newNumerator.setNumeratorAnswer(dnewNumerator);
newNumerator.setDenominatorAnswer(dnewDenominator);
I am not sure what exactly you want to do with the inputs so not adding much code here, just showing how you can set the Fraction class attributes. I don't thin you need two Fraction objects
You are trying to make a double into a fraction. You need to take the values of the double and assign it to the fraction object.
I hope this helps answer your question.
Simply change the order of your code a little to:
Scanner in = new Scanner(System.in);
System.out.println("Please enter a numerator: ");
newNumerator = new Fraction(in.nextDouble());
System.out.println("Please enter a denominator: ");
newDenominator = new Fraction(in.nextDouble());
And after this, add a constructor to your Fraction class to receive double.
//Update your constructor as..
public Fraction(double numerator, double denominator) {
this.numeratorAnswer= numerator;
this.denominatorAnswer= denominator;
}
I guess you probably knows why get the errors as stated in your commented codes. The error is caused by giving variable of different data type.
Your newNumerator and newDenominator are by datatype of Fraction. Thus you can't use it to accept double values.
In the code sample I gave, you receive the double values and pass these values into the Fraction class's numerator & denominator.

How do I execute certain commands dependent on type of input

I have a Scanner set up to ask the user to either input a number or to input "EXAMPLE" to use preset numbers. If they input a number, the code is supposed to ask them more questions and then calculate that. That executes perfectly. If the user inputs "EXAMPLE", it is supposed to set the variables to preset numbers and calculate. I can't get the code to work when EXAMPLE was entered. I get this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at CarPool.main(CarPool.java:22)
This is my code: Sorry if it is so messy.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class CarPool {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//inputs the scanner tool
float totaldistance;
float MPG;
float gasprice;
float gasused;
float totalpeople;
float totalcost;
//assigns variables
System.out.printf("Please type the total distance (miles) you are travelling, or type EXAMPLE for an example: ");
totaldistance = input.nextFloat();
if (isNan(totaldistance)) { //If the user types EXAMPLE, use preset numbers
totaldistance = 8;
MPG = 23;
gasprice = (float) 2.31;
totalpeople = 4;
} else if (isNumeric(totaldistance)); {
System.out.printf("Please enter the MPG of your vehicle: ");
MPG = input.nextFloat();
System.out.printf("Pleas enter the price of gas currently: $");
gasprice = input.nextFloat();
System.out.printf("Please enter how many people will be splitting the cost of gas:");
totalpeople = input.nextFloat();
//Prompts the user for some info that it can use for it's calculations. Sets them as floats for decimal numbers.
}
gasused = (totaldistance / MPG); //This finds how much gas the person is using by dividing the distance travelled by the mpg
totalcost = gasused * gasprice; //This calculates how much you will spend by multiplying the gas you use by the price of gas, given by the user
totalcost = totalcost / totalpeople; //splits the final cost amongst however many people are chipping in
NumberFormat formatter = new DecimalFormat("$" + "#0.00"); //Formats the price to two decimal places
System.out.println(formatter.format(totalcost)); //prints the final results
}
private static boolean isNumeric(float totaldistance) {
return false;
}
private static boolean isNan(float totaldistance) {
return false;
}
}
I'm having issues at line 22.
Obviously you will get a mismatch exception because if user enters examples you are reading it as float now you tell me can java convert example into float. no right??
So why dont you read the input data as string and check if it is example then use your preset values otherwise if it float use then accordingly
I think you should get my point.
cheers

Why System.out.printf will only work with %f when all of the variables are declared as double?

Here is my program. Just a little one for end of chapter exercises. Problem is that when I run it, it only works when I have %f in my System.printf when in my mind it should be a %d. All of my variables are double and Math.ceil returns a double so I am super confused. Could someone clarify please?
import java.util.Scanner;
public class Excersise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double enteredHours = 0;
double amountDue = 0;
System.out.printf("Please enter the number of hours parked.");
enteredHours = input.nextDouble();
amountDue = calculateCharges(enteredHours);
System.out.printf("The amount due is %f\n", amountDue); // HERE the line
// that when I
// changed it to
// %f it works,
// but again all
// variables are
// double and
// Math.ceil
// returns a
// double.
}
public static double calculateCharges(double hours) {
double roundedHours = 0;
roundedHours = Math.ceil(hours);
double charges = 2.00;
if (roundedHours > 3.0)
charges = charges + .5 * roundedHours;
if (roundedHours >= 24.0)
charges = 10.00;
return charges;
}
}
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
%d is to format an 'integer' %f is for formatting floats/doubles. I think you're mistaking '%d' to stand for double
%f is the format specifier for floating point variables whereas %d is used for integer variables.
%f is used for formatting floats/double and %d is used for decimal and In java %d is used for display the result for example :-
public class Exercise
{
public static void main(String[] args)
{
long number = 30208;
System.out.printf("Number: %d", + number);
}
}
here we use %d for display the value of long variable

Categories