2015-11-05 85 views
-2

我已經創建了一個業務程序,它帶有一個循環的double值並計算淨利潤。我需要將主類中的輸入值添加到名爲Business的自定義類中。然後,我應該計算Business類中的淨利潤並將最終值輸出到主類。當我運行我的當前程序時,結果是「0.0」。 Business類沒有從我的主類獲取我的輸入值,但我找不出原因。下面主要類:爲什麼我的程序返回「0.0」?

public class BusinessProject { 

public static double revenue; 
public static double expenses; 
public static double TotalRevenue; 
public static double TotalExpenses; 

public static void main(String[] args) { 

    Business calc = new Business(); 

    getTotalRevenue(); 
    getExpense(); 
    calc.Profit(); 

} 
public static double getTotalRevenue() {  
    Scanner scan = new Scanner(System.in); 

    while (true) { 
     System.out.println("Enter your revenue: \nJust type 0 when you've finished inputting all values"); 
     revenue = scan.nextDouble(); 
     TotalRevenue += revenue; 


    if(revenue==0) { 

     break; 
    } 
} 
    return TotalRevenue; 
} 
public static double getExpense() { 

    Scanner scan = new Scanner(System.in); 

    while (true) { 
     System.out.println("Enter your expenses: \nJust type 0 when you've finished inputting all values"); 
     expenses = scan.nextDouble(); 
     TotalExpenses += expenses; 

    if(expenses==0) { 

     break; 

     } 
    } 
    return TotalExpenses; 
} 
} 

第二個自定義類別:

public class Business { 

public static double ExpenseInput; 
public static double RevenueInput; 

public void REVENUE() { 

    BusinessProject TOTAL = new BusinessProject(); 

    double RevenueInput = BusinessProject.TotalRevenue; 

} 

public static void EXPENSE() { 

    BusinessProject TOTAL2 = new BusinessProject(); 

    double ExpenseInput = BusinessProject.TotalExpenses; 
} 

public void Profit() { 

    double difference = (RevenueInput - ExpenseInput); 

    if (difference <=1000) { 

     System.out.println("Net Profit: " + (difference - (difference * 0.00175))); 
    } 

} 

} 
+0

'商務類不是從我的主類讓我的輸入值,但我可以」不知道爲什麼 - 你沒有做任何事情來傳遞值,那麼你爲什麼期望通過輸入? – Eran

回答

0
public void Profit(BusinessProject bp) { 

    double difference = (bp.TotalRevenue - bp.TotalExpenses); 

    if (difference <=1000) { 

     System.out.println("Net Profit: " + (difference - (difference * 0.00175))); 
    } 

} 

,並調用它,如下

calc.Profit(this); 
+0

謝謝!現在工作得很好 – Jibblz

0

傳遞Business對象,而不是要創建主類新Business對象。因此,屬性將使用默認值進行初始化

你必須調用EXPENSE()和主類Profit(),你必須Business類作爲參數傳遞給這些方法

1

您得到0.0因爲您尚未調用您的方法來設置RevenueInput和ExpenseInput。

因此,在你的情況下調用EXPENSE()和REVENUE()在profit()將解決它。

不過,我建議你看看你的程序結構和命名約定。你既可以傳遞變量作爲自變量爲你的功能,如:Profit(double expense, double revenue)或者你可以有它的業務,像這樣的構造:public Business(double expense, double revenue)

你現在所擁有的是什麼,你是依靠靜態變量循環依賴您的對象(商業)隨後使用的類(BusinessProject)。

我會親自重構它是這樣的:

public class Business { 
    public static void profit(final double revenue, final double expense) { 
     double difference = (revenue - expense); 

     if (difference <=1000) { 

      System.out.println("Net Profit: " + (difference - (difference * 0.00175))); 
     } 

然後從您的主項目,你只需撥打Business.profit(TotalRevenue, TotalExpense);

相關問題