簡體   English   中英

線程“main”中的異常java.lang.Error:未解決的編譯問題:局部變量xxx可能尚未初始化

[英]Exception in thread "main" java.lang.Error: Unresolved compilation problems: The local variable xxx may not have been initialized

我無法理解。

我的錯誤

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The local variable time may not have been initialized
    The local variable time may not have been initialized

    at earth.main(earth.java:15)

我的編碼

public class Earth {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int time ;
        int distance;
        int speed ;

        distance = 150000000;
        speed = 300000;
        distance = speed * time;
        System.out.println(+time);
    }           
}

你已經聲明了int time; 但是您尚未為其分配值,因此一旦您嘗試執行speed * time ,運行時將不知道該做什么。 編譯器檢測到這一點並給你那個錯誤。

嘗試為time分配一個值,就像您對speed所做的那樣。

試試這個,例如:

int time = 10;

你需要將它初始化為一些
值之前嘗試使用它。

您已經初始化的另外兩個變量
但是你沒有初始化的time變量。

規則1:

只運行 100% 編譯的代碼。 在運行代碼之前解決所有編譯器錯誤。

規則 2:

局部變量在使用之前應該被初始化。 用一些值初始化你的時間變量。

int time = ? ;

有意思,我看你剛開始學編程,對編程和數學的關系很迷茫。

您期望編程諸如數學之類的東西。

在數學中,您定義一個方程:

1500 = 3 * time

然后您得出 answer time = 500

編程不是那樣工作的。 編程做機器做的事情,從字面上看只是:

fetch data from some memory
perform simple operation (for instance math operation + - * / )
store result back to some memory

在編程中,等號=與其數學含義大不相同。

在編程中, =被稱為assignment ,表示將計算結果存儲在哪里。 所以當你寫distance = speed * time; ,這不是數學方程式。 對機器來說,這意味着:

fetch values from memory "speed" and memory "time"
perform math multiply on the two values
store the result back to memory "distance"

顯然這不是你想要做的。 並且由於您的“時間”不包含任何值,因此 Java 編譯器會在第一步中抱怨“從 '時間' 中獲取值”。

計算機是愚蠢的,它不會為你解決數學問題,你必須清楚地寫下你的解決方案。

你真正想要的是:

time = distance / speed;

fetch values from distance and speed
perform math divide on the two values
store result back to time

祝你學習順利:)

暫無
暫無

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

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