【发布时间】:2017-11-13 21:43:36
【问题描述】:
我正在编写一个程序来收集员工的名字、姓氏和销售数据。我的所有基础都可以完美运行,但我有一个问题。在我的 while 循环中,我对其进行了编程,因此如果用户输入“添加”,那么它将调用我在不同类中创建的方法,并将他们输入的任何数字添加到员工当前的销售总额中,减法相同。但是如果我需要编写一个 if 语句来检查减法是否不成功以及是否显示“错误”。
public class EmployeeInfo
{
//class constants
//class variables
private String firstName;
private String lastName;
private int itemsSold;
private int employeeTotal;
public EmployeeInfo(String first, String last, int sold)
{
//local constants
//local variables
/******************** Start Constructor *****************/
//Calls the first and last name, and the amount of items sold
firstName = first;
lastName = last;
itemsSold = sold;
}//End constructor
public void addition(int itemsSold)
{
//local constants
//local variables
/******************** Start main method *****************/
//Adds the items sold to the employee total
employeeTotal = itemsSold + employeeTotal;
}//end addition
public void subtraction(int itemsSold)
{
//local constants
//local variables
/******************** Start main method *****************/
//Subtracts the items not sold to the employee total
employeeTotal = (employeeTotal - itemsSold);
}//end subtraction
public boolean booleanMethod(boolean result)
{
//local constants
//local variables
/******************** Start main method *****************/
if(employeeTotal < 0)
{
result = false;
}
else
{
result = true;
}
return result;
}//End booleanMethod
public String toString()
{
//local constants
//local variables
/******************************************************/
return String.format(Util.setLeft(45,"Eployee Name and Sales Figures") + "\n\n" + Util.setLeft(40, "First Name: ") + Util.setRight(30, firstName) +
"\n" + Util.setLeft(40, "Last Name : ") + Util.setRight(30, lastName) + "\n" + Util.setLeft(40, "Items Sold: ") + Util.setRight(30, Integer.toString(employeeTotal)));
}//end to string
}//end employeeInfo
这是使用 booleanMethod, 方法的类的一部分
while(soldItems != QUIT)
{
//Clear screen then prompt the user to add or subtract
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.print(Util.setLeft(35, "Add or Subtract: "));
input = Keyboard.readString();
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//if the user enters add the program will add to the employee total
if(input.equals(ADD))
{
info.addition(soldItems);
}
//else the program will subtract from the employee total
else
{
info.subtraction(soldItems);
if (info.booleanMethod(false))
{
System.out.print("Error");
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
该工具成功完成,但它不显示错误消息它只是显示我的行要求另一个销售数字,我如何让它实际工作?
【问题讨论】:
-
让减法执行验证并返回运算结果
boolean -
与其让实例处于无效状态,例如售出的商品数量为负数,不如让方法失败。例如,您的方法
EmployeeInfo.subtraction()可能会检查是否有足够的项目可供减去。如果是这样,它将执行减法并返回true;否则,它将返回false而无需执行任何其他操作。 -
@MadProgrammer 我已经试过了,但也没有用。
-
在booleanMethod方法中,对total做一个sysout,看看它有什么值。
标签: java class methods boolean