Java JDK - possible lossy conversion from double to int - java

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

Related

How to get rid of zero after decimal point?

import java.util.Scanner;
import java.lang.Math;
public class Calculator {
public static void main(String[] args) {
int firstNum;
int secondNum;
int sum;
int product;
int difference;
float division;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Number : ");
firstNum = scanner.nextInt();
System.out.print("Enter Second Number : ");
secondNum = scanner.nextInt();
scanner.close();
sum = firstNum + secondNum;
difference = firstNum - secondNum;
product = firstNum * secondNum;
division = (float) firstNum / secondNum;
double firstSquare = Math.pow(firstNum, 2);
double secondSquare = Math.pow(secondNum, 2);
System.out.println("Sum = " + sum);
System.out.println("Division = " + division);
System.out.println("Product = " + product);
System.out.println("Difference = " + difference);
System.out
.println("Square of " + firstNum + " is " + firstSquare + " Square of " + secondNum + " is " + secondSquare);
}
}
This is a program that takes in two inputs then performs few calculations. I have an issue that I don't want zero after decimal point when I am squaring two inputs. So, how do I get rid of it? Can someone help me with that. Thank you
If you don't want decimals either use an int or cast a double to an int. E.g (int) doubleValue. But if you just want to eliminate the .0 from floating point numbers then perhaps this is what you want.
for (double d : new double[]{2.3, 2.0,1.222, 4445.2, 442.0}) {
System.out.println(new DecimalFormat("#.######").format(d));
}
prints
2.3
2
1.222
4445.2
442
For more information on the format syntax, check out DecimalFormat
You can do it with formatting as follows:
System.out.format("Square of %d is %.0f Square of %d is %.0f",
firstNum, firstSquare, secondNum, secondSquare);
%d means an integer without decimal places and %.0f means a floating-point number with 0 decimal places as you wanted.
Convert to string and check for ending
public String removePrefix(double number) {
if(String.valueOf(number).endsWith(".0")) {
return String.valueOf(number).split(".0")[0];
}
return String.valueOf(number);
}
Not tested, but I hope it helps. =)
Change the double values firstSquare and secondSquare to ints and cast them to int to change from double that Math.pow() returns to int, no need to round since squares of ints will always be int
int firstSquare = (int) Math.pow(firstNum, 2);
int secondSquare = (int) Math.pow(secondNum, 2);

Possible lossy conversion while compiling in Java [duplicate]

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

How do you find the average of three numbers with input and output dialog boxes with JAVA?

I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{
public static void main(String[] args)
{
System.out.println("Enter 3 numbers: ");
Scanner input = new Scanner (System.in);
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1=input.nextInt();
num2=input.nextInt();
num3=input.nextInt();
avg=(double)(num1+num2+num3)/3.0;
System.out.println("The average is: " + decimalFormat.format(avg));
}
}
I don't know what you find hard here. I think you are looking for this:
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));
avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null, "The average is: " + decimalFormat.format(avg));
Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.
It's really not that much harder. On the input side, using one of the showInputDialog(...) methods of JOptionPane is almost an exact replacement for input.nextInt();. The only difference it that showInputDialog(...) returns the user's input as String, not an int, so you'll have to use Integer.parseInt to convert the returned String into an int. As for the output, showMessageDialog(...) is an almost exact replacement for System.out.println(...); just use the --- as the message text argument.
public static void main(String[] args) {
int num, count=0;
double total =0, avg;
for(int i = 1; i <= 3; i++){
num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++));
total += num;
}
avg = total / count;
JOptionPane.showMessageDialog(null, "The average is: " + (double)Math.round(avg * 100) / 100);
}
/*
*AverageOfThreeNumnber.java
*calculating the Average Of Four Numnberand diaply the output
*using JOptionpane method in java
*/
import javax.swing.JOptionpane;
public class AverageOfThreeNumbers {
public static void main(String[] args) {
int fristNumber; // FRIST INTEGER NUMBER
int SecondNumber; // SECOND INTEGER NUMBER
int ThridNumber; // THRID INTEGER NUMBER
int sum; // SUM OF THE FOUR INTEGER NUMBERS
double avarage; // AVERAGE OF THE FOUR NUMBERS
String input; // INPUT VALUE
String result; // OUTPUT GENERATING STRING
// ACCEPT INTEGER NUMBERS FROM THE USER
input = JOptionpane.showInputDialog(null, "Enter frist nmuber: ");
FristNumber=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Second nmuber: ");
SecondNumberr=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Thrid nmuber: ");
ThridNumber=Integer.parse.Int(Input);
//CALCULATE SUM
sum = fristNumber + SecondNumber + ThridNumber;
//CALCULATE AVERAGE
average = sum/4.0
//BUILD OUTPUT STRING AND DISPLAY OUTPUT
result = "Average of" + fristNumber + ", " + SecondNumber + " And " + ThridNumber +" is = " + average;
JOptionpane.showMessageDialog(null, result, "Average of 3 Numbers", JOptionpane.INFORMATION_MESSAGE);
}
}

Incompatible types: possible lossy conversion from double to int [duplicate]

This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 3 years ago.
Help? I don't know why I am getting this error. I am getting at in line 39:
term[1] = differentiate(Coeff[1], exponent[1]);
How can I fix this issue?
Full code listing:
public class Calcprog {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTerms = 7;
double[] Coeff = new double[6];
double[] exponent = new double[6];
String[] term = new String[6];
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
while (numTerms > 6) {
if (numTerms > 6) {
System.out.println("Please limit the number of terms to six.");
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
}
}
for (int i = 1; i < numTerms + 1; i++) {
System.out.println("Please enter the coefficient of term #" + i + " in decimal form:");
Coeff[i] = input.nextDouble();
System.out.println("Please enter the exponent of term #" + i + " in decimal form:");
exponent[i] = input.nextDouble();
}
term[1] = differentiate(Coeff[1], exponent[1]);
}
public String differentiate(int co, int exp) {
double newco, newexp;
String derivative;
newexp = exp - 1;
newco = co * exp;
derivative = Double.toString(newco) + "x" + Double.toString(newexp);
return derivative;
}
}
You are trying to pass double arguments to a method that accepts ints, which requires a casting that may result in loss of information.
You can make it work by an explicit cast :
term[1] = differentiate((int)Coeff[1], (int)exponent[1]);
Or you can change your differentiate method to accept double arguments, which would probably make more sense :
public String differentiate(double co, double exp)
your method is not static, and you calling in the main which is static, remember a non static method can be access direct in a static method, you have to create an instance of the class to access that method, and also the parameter you are passing is double and not int. Your method should be like that public static String differentiate(double co, double exp){
change the argument types of the differentiate method to double. This should then look as follows
public String differentiate(double co, double exp){
...
}

Return a range to compare with BigDecimal

In my code a user enters in a specified temperature range with this method (The default range is 0 - 100):
public class range {
public void rangeset ()
{
int range1 = 0;
int range2 = 100;
System.out.println("Please note that the default temp range is 0-100");
System.out.println("What is the starting temperature range?");
range1 = sc.nextInt();
System.out.println("What is the ending temperature range?");
range2 = sc.nextInt();
System.out.println("Your temperature range is " + range1 + " - " + range2);
HW_5.mainMenureturn();
}//end rangeset method (instance method)
}//range class
Further down, I have an input that asks the user for a number that they want to convert to Fahrenheit.
public class HW_5 {
public static double fahrenheit2Centigrade ()
{
double result;
BigDecimal quotient = new BigDecimal("1.8");
//take in input, take input as BigDecimal
System.out.println("Please enter the fahrenheit temperature you wish to convert to celsius");
BigDecimal fah = sc.nextBigDecimal();
}
}
So, what I want to do is make sure that the number they entered (which is a BigDecimal) falls within the ranges specified in the other method.
1) How do I get my rangeset method to return the beginning number of the range and the ending number of the range since you can't return two values?
2) How do I then use those returned values to check if the BigDecimal in the fahrenheit2centigrade method falls within those values?
Please ask for clarification. Thanks.
This is an issue of scope. Currently you are declaring your two range variables inside the rangeset() method, which means that they are only visible within the "scope" of the method (aka only that method has access to those variables).
What you should consider doing is instead have those variables be visible to the entire class.
public class range {
private int lowerBound;
private int upperBound;
public void rangeset ()
{
int lowerBound = 0;
int upperBound = 100;
System.out.println("Please note that the default temp range is 0-100");
System.out.println("What is the starting temperature range?");
lowerBound = sc.nextInt();
System.out.println("What is the ending temperature range?");
upperBound = sc.nextInt();
System.out.println("Your temperature range is " + range1 + " - " + range2);
HW_5.mainMenureturn();
}//end rangeset method (instance method)
public int getLowerBound()
{
return lowerBound;
}
public int getUpperBound()
{
return upperBound;
}
}//range class
Once you have things set up in this way, you can create a new range class in your main class, call the relevant methods on it, and use your getter methods to extract the data that you care about. Something like:
public class HW_5 {
public static double fahrenheit2Centigrade ()
{
double result;
BigDecimal quotient = new BigDecimal("1.8");
range myRange = new range();
myRange.rangeset();
System.out.printf("%d - %d", myRange.getLowerBound(), myRange.getUpperBound());
//take in input, take input as BigDecimal
System.out.println("Please enter the fahrenheit temperature you wish to convert to celsius");
BigDecimal fah = sc.nextBigDecimal();
}
}
Ps. Generally you should use capital letters to start your class names, ie. Range instead of range.

Categories