2015-11-05 68 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);

相关问题