Please design a method to implement the above function and return the corresponding y value according to the incoming value X.

Known functions y= x + 3 ( x > 0 ),y = 0 ( x = 0 ) y=x2 –1 ( x < 0 )
Please design a method to implement the above function , Based on the value passed in x Different , Return the corresponding y value .
Tips ： Define a static The method of decorating , Method to receive a int Parameters of type x, The return value is int type .
Use... In methods if…else if..else Statement for x The value of is used to judge three cases .
Execute different expressions according to the judgment results , And assign the result to the variable y.
Return at the end of the method y Value .
stay main Method invocation of a well designed method , Pass in a int The value of the type , Print the return value of the method .

Refer to the answer 1：
``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));    }}``

Refer to the answer 2：

Refer to the answer 3：
``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);    }    /** *  seek y Value  * * @param x  Enter the reference  * @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;    }}``

Running results ：

Refer to the answer 4：

https://cdmana.com/2021/11/20211112091851424B.html

Scroll to Top