请设计一个方法实现上面的函数,根据传入的值x的不同,返回对应的y值。

已知函数y= x + 3 ( x > 0 ),y = 0 ( x = 0 ) y=x2 –1 ( x < 0 )
请设计一个方法实现上面的函数,根据传入的值x的不同,返回对应的y值。
提示:定义一个static修饰符修饰的方法,方法接收一个int类型的参数x,返回值为int类型。
在方法中使用if…else if..else 语句针对x的值进行三种情况的判断。
根据判断结果分别执行不同的表达式,并将结果赋予变量y。
在方法的最后返回y的值。
在main方法中调用设计好的方法,传入一个int型的值,将方法的返回值打印。


public class Test {
    public static int func(int x){
        if(x>0){
            return x+3;
        }
        else if(x==0){
            return 0;
        }
        else{
            return x*x-1;
        }
    }
    public static void main(String[] args){
        System.out.println(func(-10));
    }
}
public class TestDemo{

    public static void main(String[] args) {
        int y = getValue(3);
        System.out.println("y = " + y);
        int y2 = getValue(0);
        System.out.println("y2 = " + y2);
        int y3 = getValue(-3);
        System.out.println("y3 = " + y3);
    }

    /**
     * 求y的值
     *
     * @param x 入参
     * @return y
     */
    private static int getValue(int x) {
        int y = 0;
        if (x > 0) {
            y = x + 3;
        } else if (x == 0) {
            y = 0;
        } else if (x < 0) {
            y = x * 2 - 1;
        }
        return y;
    }
}

运行结果:

img