请JAVA高手来,一道程序编程题。

来源:百度知道 编辑:UC知道 时间:2024/06/09 11:43:00
编写方法static int method1(int x)和static int method2(int x)m分别用if语句和switch语句计算如下函数的值。
f(x)=2x-1 (x<0)
3x+5 (0<=x<3)
x+1 (3<=x<5)
然后在main方法中用相同的参数依次调用这俩个方法,并判断返回结果是否相等。

static int method1(int x)
{
if(x<0)return 2*x-1;
else if(x>=0&&x<3)return 3*x+5;
else if(x>=3&&x<5)return x+1;
}

static int method2(int x)
{
switch(x)
{
case <0:return 2*x-1;
case >=0&&<3:return 3*x+5;
case >=3&&<5:return x+1;
}
}
public static void main(String args[])
{
int x=2;
if(method1(x)==method2(x))
System.out.println("equals!");
else
System.out.println("not equals.");
}

完成程序见下:
public class Test {
static int method1(int x) {
int result = 0;
if (x < 0)
result = 2 * x - 1;
else if (x < 3)
result = 3 * x + 5;
else if (x < 5)
result = x + 1;
return result;
}

static int method2(int x) {
int result = 0;
if (x < 5)
switch (x) {
case 0:
case 1:
case 2:
result =