“一个名为originalStockUp的 boolean 方法,它采用产品名称(字符串)、现有库存产品数量[int必须为非负]和每个产品的marketValue[仅限双正]作为参数。此方法设置所有类变量在调用时都正确,并返回 true,除非库房之前已第一次进货。(即,如果以前调用过此方法,则此方法返回 false。)”(不能将类变量名称用作参数)。
对于我在报价中给出的内容,我需要设置一个方法 header 。我不知道如何设置参数,使 int 为非负数,而 double 仅为正数。
我的想法:
public static boolean originalStockUp(String, int, double)
这是我的变量(在方法之外):
static int countOfProduct = -1;
static String productName = "Not set yet.";
static double marketValuePer = 0.0;
final static String MY_NAME = "Name";
这是我的主要方法(如果有帮助的话):
public static void main (String[] args)
{
showStock();
if (!originalStockUp("Yoyo", 500, 4.75))
reportErrorAndBomb("First call to stock up failed. Why?");
showStock();
if (originalStockUp("Pen", 1500, 1.01))
reportErrorAndBomb("Second call to stock up succeded. Why?");
if (stockCount() != 500)
reportErrorAndBomb("Inventory count is now off. (500)");
if (addStock(-100))
reportErrorAndBomb("You let me add -100?? Why?");
if (! addStock(100))
reportErrorAndBomb("Adding 100 failed. Why?");
if (getValue() != 4.75)
reportErrorAndBomb("How did our product value get off? ($4.74)");
setValue(4.85); //Inflation...
if (getValue() != 4.85)
reportErrorAndBomb("How did our product value get off? ($4.85)");
if (inventoryBalance() != 2910.00)
reportErrorAndBomb("Hmm issue with value of full inventory?");
if (stockCount() != 600)
reportErrorAndBomb("Inventory count is now off. (600)");
showStock();
//Just test the error reporter code.
reportErrorAndBomb("Bye bye - all actually went well!");
}//End Method: Main
}//End class: Program 4.
第一次不得不编写一个非 main 的方法。抱歉,如果问题太模糊或太基本。
最佳答案
I wasn't sure how to set the parameters so that int is a non-negative, and double is positive only.
您无法在 Java 的方法签名中强制执行这种约束。 (有一两种编程语言支持具有范围约束的类型......但这不是主流语言功能。)
您应该做的是在方法内添加一些代码,以在运行时验证调用它的参数,并在违反范围约束时抛出异常。例如:
if (param < 42) {
throw new IllegalArgumentException("param is too small: " + param);
}
(理论上,您可以使用 assert
而不是显式测试/抛出。但是,默认情况下断言检查是禁用的,并且您通常不希望它可以“关闭”输入验证。)
关于java - 创建具有 3 个参数的 boolean 方法(String、int [非负]、double [仅限正]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267419/