📜  Java中的句点 isNegative() 方法及示例(1)

📅  最后修改于: 2023-12-03 14:42:56.213000             🧑  作者: Mango

Java中的句点 isNegative() 方法及示例

在Java的Integer类中,有一个句点方法isNegative(),用来判断一个整数是否为负数。如果该整数小于零,则返回true,否则返回false

该方法的定义如下:

public static boolean isNegative(int value) {
    return value < 0;
}

以下是一个示例程序,展示如何使用isNegative()方法:

public class Main {
    public static void main(String[] args) {
        int x = -10;
        int y = 20;
        
        if (Integer.isNegative(x)) {
            System.out.println(x + " is negative.");
        } else {
            System.out.println(x + " is not negative.");
        }
        
        if (Integer.isNegative(y)) {
            System.out.println(y + " is negative.");
        } else {
            System.out.println(y + " is not negative.");
        }
    }
}

输出结果为:

-10 is negative.
20 is not negative.

在上面的程序中,我们首先定义了两个整数变量xy,分别为负数和正数。然后我们使用了isNegative()方法来判断它们是否为负数,如果是则输出相应的信息,否则输出该数不是负数的信息。

值得注意的是,isNegative()方法只适用于int类型,如果你想判断其他类型的数是否为负数,则需要使用其他方法或自行实现判断逻辑。

总之,isNegative()方法是Java中非常便捷的用于判断整数是否为负数的方法,适用于各种场景。