2014-10-26 73 views
-1
import java.util.*; 
public class lab81 
{ 

public static void main(String args []) 
{ 
    Scanner input = new Scanner(System.in); 

    System.out.print("Enter Last Name"); 
    String LASTNAME; 
    LASTNAME = input.nextLine();  
    System.out.print("Enter First name"); 
    String FIRSTNAME; 
    FIRSTNAME = input.nextLine(); 

    System.out.print("Enter this years units"); 
    double presentyearsUnits; 
    presentyearsUnits = input.nextInt(); 

    System.out.print("Enter last year's units"); 
    double lastyearsUnits; 
    lastyearsUnits = input.nextInt(); 

    final int RANGE1 = 1000; 
    final int RANGE2 = 3000; 
    final int RANGE3 = 6000; 
    final int BONUS0 = 0; 
    final int BONUS1 = 25; 
    final int BONUS2 = 50; 
    final int BONUS3 = 100; 
    final int BONUS4 = 200; 

    int bonus; 

    { 
    if(lastyearsUnits >= presentyearsUnits) 
    bonus= BONUS0; 

else if(presentyearsUnits <= RANGE1) 
    bonus= BONUS1; 

else if(presentyearsUnits<=RANGE2) 
    bonus= BONUS2 ; 

else if(presentyearsUnits <=RANGE3) 
    bonus= BONUS3; 

else if(presentyearsUnits>=RANGE3) 
    bonus=BONUS4; 
    } 

**System.out.println(("LASTNAME" + "," + "FIRSTNAME:" + "$") + bonus);** 


} 

} 

當我編譯我不斷收到此錯誤關於未初始化的獎金。我一直在努力解決這個問題,但目前爲止我失敗了。我不知道如何初始化可變獎金。編譯器在system.out.print中突出顯示獎金。可變獎金可能尚未初始化。

回答

0

當你定義bonus變量,你忘了初始化。

int bonus; 

變化

int bonus=0 ; 

閱讀這個答案更多信息

局部變量沒有得到默認值。它們的初始值是 未定義,但通過某種方式分配值。在你使用 局部變量之前,它們必須被初始化。

當您在課程級別 (作爲成員即作爲字段)和方法級別聲明變量時存在很大差異。

如果您在聲明類級別字段,他們根據自己的類型得到的默認值 。如果您在方法級別或 爲塊聲明變量(指anycode內{})沒有得到任何價值,並保持 不確定的,直到一些他們如何得到一些初始值,即分配給他們一些值 。

Source of the Answer

+1

不,這是一個真實的重複問題。 – Makoto 2014-10-26 23:26:53

+0

@Makoto **和我投下的原因是?!!!!!!!! ** – 2014-10-26 23:28:14

+1

誰說這是我壓低了你的?我所說的是,你的回答不會在你所鏈接的內容之外添加任何其他內容。 – Makoto 2014-10-26 23:31:26

0

編譯器看到的,這是可能的獎金尚未初始化。這意味着獎金沒有被分配一個值。請參閱以下示例:

int var; 
String input = // something the user has inputted 

if (input.equals("foo")) { 
    var = 1; 
} 

System.out.println(var); // var not necessarily initialized. will not compile. 

在此示例中,可能var尚未被「初始化」。如果用戶輸入了「foo」以外的內容,則是這種情況。你應該做以下幾點:

int bonus = 0; // initial value 
+0

如果任何變量未初始化,程序將不會被編譯。 – 2014-10-26 23:21:00

+1

@KickButtowski我認爲我的回答傳達了這個信息? – 2014-10-26 23:22:05