2008-10-28 36 views
1

Java在執行加法時如何處理長變量?爲什麼添加長變量會導致連接?

版本錯誤1:

Vector speeds = ... //whatever, speeds.size() returns 2 
long estimated = 1l; 
long time = speeds.size() + estimated; // time = 21; string concatenation?? 

版本錯誤2:

Vector speeds = ... //whatever, speeds.size() returns 2 
long estimated = 1l; 
long time = estimated + speeds.size(); // time = 12; string concatenation?? 

正確的版本:

Vector speeds = ... //whatever, speeds.size() returns 2 
long estimated = 1l; 
long size = speeds.size(); 
long time = size + estimated; // time = 3; correct 

我不明白,爲什麼Java的將它們連接起來。

任何人都可以幫助我,爲什麼兩個原始變量是連接的?

問候,guerda

+1

提示:不要使用「L」爲多頭,因爲它是從「1」沒有區別在某些字體。改用'L'。 – toolkit 2008-10-28 12:18:06

+0

你已經接受了一個答案,但是沒有完全解釋是什麼導致了這個問題 - 你能否詳細說明一下? – paxdiablo 2008-10-28 12:45:47

回答

4

我懷疑你沒有看到你認爲你所看到的。 Java不會這樣做。

請嘗試提供一個short but complete program來說明這一點。這是一個簡短但完整的程序,它表明了正確的行爲,但是卻帶有「錯誤的」代碼(即反例)。

import java.util.*; 

public class Test 
{ 
    public static void main(String[] args) 
    { 
     Vector speeds = new Vector(); 
     speeds.add("x"); 
     speeds.add("y"); 

     long estimated = 1l; 
     long time = speeds.size() + estimated; 
     System.out.println(time); // Prints out 3 
    } 
} 
21

我的猜測是,你實際上是在做喜歡的事:

System.out.println("" + size + estimated); 

這個表達式被從左到右依次爲:

"" + size  <--- string concatenation, so if size is 3, will produce "3" 
"3" + estimated <--- string concatenation, so if estimated is 2, will produce "32" 

爲了得到這個工作,你應該做的:

System.out.println("" + (size + estimated)); 

再次這是從左向右計算:

"" + (expression) <-- string concatenation - need to evaluate expression first 
(3 + 2)   <-- 5 
Hence: 
"" + 5   <-- string concatenation - will produce "5" 
相關問題