2015-09-23 38 views
-4

我正在嘗試創建一個「Class」:Sandwich.Java「Application」:testSandwich.java。如何使用java設置並獲取

我的任務是包括方法來獲取和設置Sandwich.java中3個字段的值: 主要成分,麪包類型,價格。 然後在應用程序中,實例化數組中的五個三明治對象。 (五門陣列)

Sandwich.java:

public class Sandwich { 
    public String mainIngredient = ""; 
    public String breadType = ""; 
    public Double price; 

    String getMainIngredient(){ 
     return mainIngredient; 
    } 

    void setMainIngredient(String mainIng){ 
     mainIngredient = mainIng; 
    } 

    void setBread(String wheat){ 
     breadType = wheat; 
    } 

    void setPrice(double mainPrice){ 
     price = mainPrice; 
    } 

testSandwich.java:

public class TestSandwich { 

    public static void main(String args[]) { 

       Sandwich[] sandwiches = new Sandwich[5]; 


       for(int i = 0; i < 5; i++){ 
       sandwiches[i] = new Sandwich(); 

       System.out.println("Choose a Main Ingredient: "); 
       String userInput = user_input.next(); 
       sandwiches[i].setBread(userInput); 

       System.out.println("Choose a Bread: "); 
       userInput = user_input.next(); 
       sandwiches[i].setMainIngredient(userInput); 

       System.out.println(sandwiches[i].getMainIngredient()); 
       System.out.println(""); 

電流誤差輸出:

選擇主要成分:在螺紋

異常 「主」 了java.lang.RuntimeException:不可編譯的源代碼 - 錯誤的符號類型:user_input.next

at practical.TestSandwich.main(TestSandwich.java:24) 

Java結果:1

生成成功(總時間:1秒)

問題:我該如何解決這個錯誤,以及如何獲得我期待的結果?

+0

首先,我強烈建議您不要嘗試運行無法編譯的代碼。確保你的代碼首先編譯 - 如果你提供了運行沒有正確編譯的代碼的選項,*說不要*,除非你有特殊原因想要儘可能運行無效代碼。 –

+0

至於這個錯誤 - 這與getter和setter方法無關......你試圖調用一個'user_input'變量的方法,但是你還沒有聲明。也許你在'main'方法開始時缺少'Scanner user_input = new Scanner(System.in);'' (我強烈建議你不要使用下劃線來命名變量,並且*當然*沒有在同一個方法中同時調用'user_input'和'userInput'的變量......非常令人困惑。) –

+0

你在哪裏聲明瞭user_input? – Rehman

回答

1

由於您根本沒有啓動Scanner user_input,因此執行該操作。試試這個在您的main()函數的開始:

Scanner user_input = new Scanner(System.in); 

這裏是一個基本的教程如何處理掃描對象和用戶輸入: http://www.homeandlearn.co.uk/java/user_input.html

我也強烈建議您,做您選擇之前的一些研究張貼您的問題。你也應該明白你的程序的功能,否則你根本不會理解你的問題(因爲這次是這樣)。