Scanner scan=new Scanner(System.in);
System.out.println("请选择一个车型(1.夏利2.宾利3.桑塔纳)");
int n=scan.nextInt();
System.out.println("请输入行驶的千米数");
int km=scan.nextInt();
double sum=0;
switch(n){
case 1:
if(km<=3){
sum=3;
}else{
sum=3+(km-3)*2.1;
}
break;
case 2:
if(km<=3){
sum=3;
}else{
sum=4+(km-3)*2.4;
}
case 3:
if(km<=3){
sum=3;
}else{
sum=5+(km-3)*2.7;
}
}
System.out.println("请输入行驶的千米数"+sum);
把每个else...if 换成(布尔型的表达式)?表达式1:表达式2 ==》
代码:
Scanner scan=new Scanner(System.in);
System.out.println("请选择一个车型(1.夏利2.宾利3.桑塔纳)");
int n=scan.nextInt();
System.out.println("请输入行驶的千米数");
int km=scan.nextInt();
double sum=0;
switch(n){
case 1:
sum=km<3?3:3+(km-3)*2.1;
break;
case 2:
sum=km<3?3:4+(km-3)*2.4;
case 3:
sum=km<3?3:5+(km-3)*2.7;
}
System.out.println("请输入行驶的千米数"+sum);
}
把两个改变的量:千米数和加价的价钱提取出来 ==》
代码:
Scanner scan=new Scanner(System.in);
System.out.println("请选择一个车型(1.夏利2.宾利3.桑塔纳)");
int n=scan.nextInt();
System.out.println("请输入行驶的千米数");
int km=scan.nextInt();
double sum=0;
int x=0;
double y=0;
switch(n){
case 1:
x=3;
y=2.1;
break;
case 2:
x=4;
y=2.4;
case 3:
x=5;
y=2.7;
}
sum=km<=3?x:x+(km-3)*y;
System.out.println("请输入行驶的千米数"+sum);
把千米数和加价的价钱放入分别放入两个个数组中:
代码:
Scanner scan=new Scanner(System.in);
System.out.println("请选择一个车型(1.夏利2.宾利3.桑塔纳)");
int n=scan.nextInt();
int[] che={3,4,5};
double[] kmshu={2.1,2.4,2.7};
System.out.println("请输入行驶的千米数");
int km=scan.nextInt();
double sum=0;
sum=km<=3?che[n-1]:che[n-1]+(km-3)*kmshu[n-1];
System.out.println("请输入行驶的千米数"+sum);
}