import java.util.Scanner;//导入Scanner类
public class function {
public static void main(String[] args) { //主方法入口
Scanner scan=new Scanner(System.in);
char ch='y';
double t1,y,t;
while(ch=='y'){ //可以反复输入t
System.out.println("Please input a number");//提示输入
t=scan.nextDouble(); //输入数字
t1=t; y=0;
//以下是if语句
if(t>=0&&t<1)
y=t*t-1;
if(t>=1&&t<3)
y=t*t*t-2*t-2;
if(t>=3&&t<5)
y=t*t-t*Math.sin(t);
if(t>=5&&t<7)
y=t+1;
if(t>=7||t<0)
y=t-1;
System.out.println("Using the if statement, the result is y="+y);//输出结果
//以下是switch语句
int m=(int)t1;
double y1;
switch(m){
case 0:y1=t1*t1-1;break;
case 1:
case 2:y1=t1*t1*t1-2*t1-2;break;
case 3:
case 4:y1=t1*t1-t1*Math.sin(t1);break;
case 5:
case 6:y1=t1+1;break;
default:y1=t1-1;break;
}
System.out.println("Using the switch statement, the result is y="+y1); //输出结果
System.out.println("If you want to continue test,please input character 'y'," +
"or input other character to exit");
String str=scan.next();
ch=str.charAt(0);//输入字符来判断是否进行测试
}
System.out.println("Exit the program");//退出程序
}
}
Java(if-switch的使用)
最新推荐文章于 2024-04-28 15:03:14 发布