2012-10-04 48 views
0

im正在處理的代碼旨在接受來自用戶的輸入,但是每當我運行該程序時,它都會告訴我存在錯誤java.land。 nullexception:null。我不知道該怎麼辦!繼續獲取java.lang.nullexception的錯誤:null

import java.util.Scanner; 

public class HamzasGrocery 
{ 
// instance variables - replace the example below with your own 
private Scanner in; 

/** 
* Constructor for objects of class HamzasGrocery 
*/ 
public HamzasGrocery() 
{ 
    Scanner in = new Scanner(System.in); 
} 

/** 
* An example of a method - replace this comment with your own 
* 
* @param y a sample parameter for a method 
* @return  the sum of x and y 
*/ 
public void sampleMethod() 
{ 
double choice1; 
double choice2; 
double choice3; 
double choice4; 
double choice5; 
double total; 

System.out.print("Enter item #1: "); 
System.out.println(); 
choice1 = in.nextDouble(); 
System.out.print("Enter item #2: "); 
choice2 = in.nextDouble(); 
System.out.println(); 
System.out.print("Enter item #3: "); 
choice3 = in.nextDouble(); 
System.out.println(); 
System.out.print("Enter item #4: "); 
choice4 = in.nextDouble(); 
System.out.println(); 
System.out.print("Enter item #5: "); 
choice5 = in.nextDouble(); 
System.out.println(); 

System.out.printf("%-10s", "Item #'s"); 
System.out.printf("%-10s", "Cost:"); 
System.out.printf("%-10s", "Total:"); 

} 

}

回答

4

得到了在構造函數中擺脫了掃描儀的「在=新條碼掃描儀。」代碼。 。

這樣做的聲明它是現在的樣子,你說的是,在屬於本地範圍,從而忽略了實例變量

所以構造應該是:

public HamzasGrocery() 
{ 
    in = new Scanner(System.in); 
} 
1

在你的構造函數中,你正在初始化一個新的掃描器,而不是你的實例變量Scanner。試試這個:

public HamzasGrocery() 
{ 
    in = new Scanner(System.in); 
}