簡體   English   中英

如何比較一個整數和一個長?

[英]How to compare an Integer with a long?

我試圖檢查一個長整數是否大於INTEGER.MAX值,但它不起作用。 這是非常直接的所以我只是想知道將Integer對象與我所做的長對象進行比較是否有問題,因為否則我不知道問題是什么。 在nextTotal值超過INTEGER.MAX時,它會輸入負數而不是打印錯誤消息。

public Integer initialValue=0;

int amount = Integer.parseInt(amountStr);
        System.out.println("Received from client: " + amount);

        long nextTotal=amount+initialValue;
            if((nextTotal>Integer.MAX_VALUE)||    (nextTotal<Integer.MIN_VALUE)){
                System.out.println("Error: Integer has not been added as the total exceeds the Maximum Integer value!");
                out.flush();
            }  

            else{
                initialValue+=amount;
                out.println(initialValue); //server response
                System.out.println("Sending total sum of integers to the client:"+initialValue);
                out.flush();
                }
            }

問題是你已經添加了兩個int ,但它們還沒有被提升為long ,所以它在轉換為long之前溢出,當然int永遠不會大於Integer.MAX_VALUE 它只會在轉移后轉換為long轉換。

在添加之前轉換為很long ,使用強制轉換。

long nextTotal = (long) amount + initialValue;

既然你真的不想使用long值,我通常會做這樣的檢查:

int amount = Integer.parseInt(amountStr);
if (amount > (Integer.MAX_VALUE - initialValue)) 
  throw new IllegalArgumentException("Amount exceeds maximum value");
initialValue += amount;

換句話說,在添加之前檢查金額是否會溢出,並拋出異常(或發送錯誤消息或適合您的應用程序的任何內容)而不是正常進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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