2

This is another newbie question. I have been working this type of error for the last couple of days and have been getting nowhere so it is time to ask you, the adoring wonders of the Java world.

I'm getting the error that there cannot be converted from double to int.

This is the code that I have written:

out.printf("Enter the price of the first article:");
    double priceFirstArticle = in.nextDouble();
    int i = priceFirstArticle; //ERROR*****//

    out.printf("Enter the price of the second article:");
    double priceSecondArticle = in.nextDouble();
    int s = priceSecondArticle; //ERROR*****//

    out.printf("Enter the price of the third article:");
    double priceThirdArticle = in.nextDouble();
    int t = priceThirdArticle; //ERROR*****//

How can I fix this error?

Thank you for your help,

Northwill

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • change `int` to `double` – Ravi Sep 22 '18 at 17:37
  • 3
    Please read: _[What's the difference between JavaScript and Java?](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java)_ – Luca Kiebel Sep 22 '18 at 17:38
  • you can not convert double to int this way. Please read this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – zappee Sep 22 '18 at 17:46
  • @L.NorthWill : Any of our answers worked for you? If yes please accept one. – Nicholas K Sep 23 '18 at 10:27

4 Answers4

1

If you want to convert a double to an int you need to explicitly cast it

double priceFirstArticle = in.nextDouble();
int i = (int) priceFirstArticle;

or change double to int as follows :

int priceFirstArticle = in.nextInt();
int i = priceFirstArticle; 
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
0

Converting from a double to an int may lose information, so Java doesn't allow it out of the box. If you want to do this, you need to be explicit about it, e.g., by casting:

int i = (int) priceFirstArticle;
// Here-^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

There remains a lot of ways...

you can not just type int i = priceFirstArticle; to convert it into int.

Some of them are

Double d = new Double();
int i = d.intValue();

or

you can use Math.round(double).

but the first one is much preferable.

-1

first, You have to use wrapper class (Double, Integer, ecc) for the primitive type (double, int,...).

In java > 1.5 boxing and unboxing is automatic.

Double priceFirstArticle = in.nextDouble();
    int  i = priceFirstArticle.intValue();
 ........
musicrizz
  • 61
  • 1
  • 2