1.实验内容
已知
x + 3 ( x > 0 )
y = 0 ( x = 0 )
x2 –1 ( x < 0 )
请设计一个方法实现上面的函数,根据传入的值x的不同,返回对应的y值。
2.解题思路
首先需要定义一个add方法实现上述函数,由于程序需要输入x的值,接收用户从键盘上录入的整数,所以要用Scanner类创建一个reader对象,读取用户在命令行输入的int数据类型,接下来定义一个求函数的方法,接收参数,其中a为函数x,使用if...else if...else语句实现x在不同的范围下y的取值,最后将方法的返回值打印。
3.程序代码
import java.util.*; //导入,用在声明类的前面
public class test1
{
public static void main(String[] args){
Scanner reader=new Scanner(System.in); //使用Scanner类创建一个reader对象
System.out.println("请输入一个整数");
int x=reader.nextInt(); //读取用户在命令行输入的int数据类型
int y;
y=add(x); //调用add()方法
System.out.println("y =" +y);
}
public static int add(int a){ //定义一个求函数的方法,接收参数,其中a为x的值
int temp; //使用变量temp存储运算结果
if(a>0){
temp=a+3;}
else if(a==0){
temp=0;}
else{
temp=a*a-1;}
return temp; //将变量temp的值返回
}
}
4.运行结果
5.运用到的知识
方法的定义与使用;
需要用到Scanner类,由于Scanner类位于java.util包中,所以在声明类的前面要导入import java.util.*;