2014-03-24 78 views
0

我想檢查長整數是否大於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(); 
       } 
      } 

回答

2

的問題是,你已經添加了兩個int S中,但還沒有被提升到long呢,所以它被轉換爲long之前溢出,當然還有一個int不能超過Integer.MAX_VALUE更大。只有在分配後纔會轉換爲long,這是在添加之後。

在添加之前轉換爲long

long nextTotal = (long) amount + initialValue; 
+0

感謝您的幫助 - 我覺得這很簡單! – kellzer

0

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

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

換句話說,檢查量是否會溢出後再加入,並拋出一個異常(或發送錯誤信息或任何適合您的應用程序的內容)而不是正常進行。