流程控制语句
了解流程控制语句最直接的办法是上例子分析
-
if条件语句
例子:企业发放的奖金根据利润提成。利润低于或等于10万元时,奖金可提10%; 利润高于10万元,低于或等于20万元时,高于10万元的部分,可提成7.5%; 高于20万,低于或等于40万时,高于20万元的部分,可提成5%; 高于40万,低于或等于60万时,高于40万元的部分,可提成3%; 高于60万,低于或等于100万时,高于60万元的部分,可提成1.5%, 高于100万元时,超过100万元的部分按1%提成, 输入一个整数变量为当月利润,求应发放奖金总数?
import java.util.Scanner;
public class Answer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double x = 0,y = 0;
System.out.print("输入当月利润(万):");
Scanner s = new Scanner(System.in);
x = s.nextInt();
if(x > 0 && x <= 10) {
y = x * 0.1;
} else if(x > 10 && x <= 20) {
y = 10 * 0.1 + (x - 10) * 0.075;
} else if(x > 20 && x <= 40) {
y = 10 * 0.1 + 10 * 0.075 + (x - 20) * 0.05;
} else if(x > 40 && x <= 60) {
y = 10 * 0.1 + 10 * 0.075 + 20 * 0.05 + (x - 40) * 0.03;
} else if(x > 60 && x <= 100) {
y = 20 * 0.175 + 20 * 0.05 + 20 * 0.03 + (x - 60) * 0.015;
} else if(x > 100) {
y = 20 * 0.175 + 40 * 0.08 + 40 * 0.015 + (x - 100) * 0.01;
}
System.out.println("应该提取的奖金是 " + y + "万");
s.close();
}
}
if()中的表达式为true则执行对应代码块,否则执行else对应代码块。
-
switch语句
例子:输入一个成绩a,使用switch结构求出a的等级。 A:90-100,B:80-89,C:70-79,D:60-69,E:0~59
-
while循环
import java.util.Scanner;
public class Answer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
double score = scanner.nextDouble();
System.out.println("请输入成绩\n");
int key = (int)score/10;
switch (key) {
case 10:
case 9:
System.out.println("A");
break;
case 8:
System.out.println("B");
break;
case 7:
System.out.println("C");
break;
case 6:
System.out.println("D");
break;
default:
System.out.println("E");
break;
}
scanner.close();
}
}
switch支持的数据类型int、byte、short、char
JDK7指出枚举类型等
执行流程 switch中的key指与case值进行匹配,跳转到对应case后执行代码块。default中的值是case以外的值。
-
do-while循环
猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个, 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 以后每天早上都吃了前一天剩下的一半零一个。 到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
public class Answer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 1;
int day = 9;
do{
sum =(sum+1)*2;
day--;
}while(day>=1);
System.out.println("第一天共摘了"+sum+"个");
}
}
写do–while循环语句时,注意while();分号不能忘。
还有不能条件是否为true,do{}代码块都会在最开始先执行一次。
-
for循环
编写一个程序,找出大于200的最小的质数
public class Answer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 200; i < 300; i++) {
boolean flog = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
flog = false;
break;
}
}
if (!flog) {
continue;
}
System.out.println(i);
break;
}
}
}
for循环中的
- 表达式1循环起点的初始化变量值
- 表达式2循环判断
- 表达式3作为控制流程的关键点