![](/img/trans.png)
[英]I converted double to int, but there is still an error, explain why?
[英]I get the error that there can't be converted from double to int
这是另一个新手问题。 在过去的几天里,我一直在处理这种类型的错误,但是却一无所获,所以现在该问您一个Java世界的奇观了。
我收到了无法从double转换为int的错误。
这是我编写的代码:
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*****//
如何解决此错误?
谢谢您的帮助,
Northwill
如果要将double
int
转换为int
,则需要显式转换
double priceFirstArticle = in.nextDouble();
int i = (int) priceFirstArticle;
或将double更改为int,如下所示:
int priceFirstArticle = in.nextInt();
int i = priceFirstArticle;
从double
转换为int
可能会丢失信息,因此Java不允许开箱即用。 如果要执行此操作,则需要对此进行明确说明,例如,通过强制转换:
int i = (int) priceFirstArticle;
// Here-^
还有很多方法...
您不能只输入int i = priceFirstArticle;
将其转换为int
。
他们之中有一些是
Double d = new Double();
int i = d.intValue();
要么
您可以使用Math.round(double)
。
但第一个更可取。
首先,必须对原始类型(double,int,...)使用包装器类(Double,Integer,ecc)。
在Java> 1.5中,装箱和拆箱是自动的。
Double priceFirstArticle = in.nextDouble();
int i = priceFirstArticle.intValue();
........
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.