簡體   English   中英

我收到了無法從double轉換為int的錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM