条件分支语句的区别和联系:
if-else if-else语句与switch-case语句 :
本程序可以包含switch-case 语句结构,代码示例如下:
import java.util.Scanner;
public class Try2 {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x;
@SuppressWarnings("unused")
double f;
int r;
x = scan.nextDouble();
if(x<0) {
r = 1;
}
else if(x==0) {
r = 2;
}
else {
r = 3;
}
switch(r) {
case 1:
System.out.println(f = -1);
break;
case 2:
System.out.println(f = 0);
break;
case 3:
System.out.println(f = 2*x);
break;
}
scan.close();
}
}
但是会有为了用switch-case语句而用的嫌疑,其实个人最简单的操作应该是直接用if-else if-else语句。实例代码如下:
import java.util.Scanner;
public class Try2 {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x;
double f;
//int r;
x = scan.nextDouble();
if(x<0) {
//r = 1;
f = -1;
}
else if(x==0) {
//r = 2;
f = 0;
}
else {
//r = 3;
f = 2*x;
}
/*switch(r) {
case 1:
System.out.println(f = -1);
break;
case 2:
System.out.println(f = 0);
break;
case 3:
System.out.println(f = 2*x);
break;
}*/
System.out.println(f);
scan.close();
}
}
如果有更好的switch-case实现,请大家在评论区@我哦。