java - 创建具有 3 个参数的 boolean 方法(String、int [非负]、double [仅限正])

标签 java methods parameters

“一个名为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/

相关文章:

java - 关于Java函数调用

javascript - Knockout.js:函数参数未定义

c# - 当不能简单地重载时混合可选参数和参数

c++ - 将 C++ 函数指针传递给 Fortran 子例程

java - Eclipse/maven - “无法将项目方面 EAR 的版本更改为 6.0

java - 使用java从postgres数据库表中删除数千行的最快方法

java - 在 java 方法中省略 public 修饰符

java - Maven wildfly-maven-plugin 自定义standalone.xml

java - Netbeans 如何在编码时发现错误

java - # 在 Java 方法中起什么作用?