我创建了一个业务程序,它通过循环获取双值并计算净利润。我需要将主类的输入值添加到名为Business的自定义类中。然后我应该计算Business类中的净利润并将最终值打印到主类。当我运行当前程序时,结果为“0.0”。 Business类没有从我的主类中获取输入值,但我无法弄清楚原因。主要课程如下:
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 :(得分:1)
你得到0.0因为你没有调用你的方法来设置RevenueInput和ExpenseInput。
所以在你的情况下,在profit()解决之前调用EXPENSE()和REVENUE()。
但是,我建议你查看你的程序结构和命名约定。您可以将变量作为函数的参数传递,例如:Profit(double expense, double revenue)
,或者您可以在Business的构造函数中将其作为:public Business(double expense, double revenue)
你现在拥有的是一个循环依赖,你依赖于你的对象(Business)所使用的类(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);
答案 1 :(得分:0)
而不是传递Business
对象,而是在主类中创建新的Business
对象。因此,属性将使用默认值
您必须从主类调用EXPENSE()
和Profit()
,并且必须将Business
类作为参数传递给这些方法
答案 2 :(得分: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);