2015-04-06 34 views
1

我目前正在學習有關方法和使用方法。在決定在參數中放置什麼時,它有時會混淆我的想法。我有一些代碼,我創建了三種方法,都符合。我必須爲此計劃做的事情是顯示一些服務和價格,並詢問用戶他/她是否願意。如果他們說是的話,那麼價格會加在陣列的末尾。我遇到麻煩的部分是如何在我的第三種方法中從主要價格中獲取價格。我知道我應該使用無效方法,因爲我沒有返回任何東西,只是將價格打印出來給用戶。 繼承人我的代碼對這一計劃:Java中的方法 - 無效

static Scanner keyboard = new Scanner(System.in); 

public static void main(String[] args) { 
    System.out.println("What automobile make do you own?"); 
    Scanner keyboard = new Scanner(System.in); 

    String name = keyboard.nextLine(); 
    make(name); 

    double price = carMaintenance(name); 
    finalPrice(price); 

} 

// First Method 
public static void make(String name) { 
    System.out.println("Hello! We will be happy to service your " + name 
      + " automobile today!"); 
} 

// Second Method 
public static double carMaintenance(String name) { 
    String[] services = { "Oil Change", "Tire Rotation", "Air Filter", 
      "Check Fluids" }; 
    double[] prices = { 39.99, 49.99, 19.99, 10.99 }; 
    double Total = 0; 

    for (int i = 0; i < services.length; i++) { 
     System.out.println("Do you want a " + services[i] + " for your " 
       + name + " " + prices[i] + "? (y/n)"); 
     String answer; 
     answer = keyboard.nextLine(); 
     if (answer.equals("y")) 
     { 
      Total = Total + prices[i]; 
     } 
// Third method 
    public static void finalPrice (?) 

具體這個我有麻煩的部分:

//第三種方法 公共靜態無效finalPrice(雙價)

問題是finalPrice是一個非常混淆的變量的無效類型。

+1

是什麼使它不同於'carMaintenance' /'make'?你在那裏傳遞一個值。 – Maroun 2015-04-06 12:33:46

回答

2

你必須改變finalPrice()接受double參數:

public static void finalPrice(double price) { ... } 

而且路過carMaintenance()finalPrice()返回值:

double price = carMaintenance(name); 
finalPrice(price); 

注意我假設你只是忘了粘貼休息的carMaintenance()方法。最後,當然,它應該有return Total聲明。

+0

哦,我明白了,但是爲什麼它說void是finalPrice的無效數據類型? – Chang852 2015-04-06 12:48:40

+0

@ Chang852你是否聲明'finalPrice'是一個方法('public static void finalPrice(double price){// code here}')還是一個變量('public static void finalPrice;')? – 2015-04-06 12:52:33

+0

我宣稱它是一種方法。 – Chang852 2015-04-06 12:56:59

0

你的第二種方法是缺少返回語句。從carMaintance

public static void main(String[] args) { 
    System.out.println("What automobile make do you own?"); 
    Scanner keyboard = new Scanner(System.in); 

    String name = keyboard.nextLine(); 
    make(name); 

    double finalPrice = carMaintenance(name); 
    printFinalPrice(finalPrice); 
} 

//first method code here 

public static double carMaintenance(String name) { 
    //second method code here, plus: 
    return total; 
} 

// Third method 
public static void printFinalPrice(double finalprice) { 
    System.out.println("Your final price is " + finalprice); 
} 
0

通雙待finalPrice

double finalPriceDbl = carMaintenance(name); 
finalprice(finalPriceDbl); 

和finalPrice

public static void finalPrice (double finalPrice); 
接受雙重的參數:您可以將總返回主,然後將它發送給你的第三個方法,因爲這樣

同樣你應該返回汽車維修與返回狀態值

return Total;