条件语句
if(yourSales >= target){
performance = "Satisfactory"
Bonus = 100;
}
if (yourSales >= target){
performance = "Satisfactory"
Bonus = 100;
}
else{
performance = "Unsatisfactory"
Bonus = 0;
}
if...elseif...else
if (yourSales >= 2*target){
performance = "Excellent";
Bonus = 1000;
}
else if (yourSales >= 1.5*target){
performance = "Fine";
Bonus = 500;
}
else if (yourSales >= target){
performance = "Satisfactory";
Bonus = 100;
}
else{
System.out.println("You're fired");
}
多重选择 switch
switch(choice)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}
循环
while
当条件为 true,while循环执行一个语句块
当条件为 false, while循环体一次也不执行
while(balance < goal){
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years ++;
}
do/while
先执行一次语法块,再检测循环条件;然后重复语句,再检测循环条件,以此类推
do{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years ++;
}
while( balance < goal )
for
for(int i=1; i<= 10; i++) //迭代10次
中断流程
break
while(years <= 100){
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if(balance >= goal) break;
years++;
}
如果在循环体中 balance>= goal, 则退出循环语句
continue
continue 语句将控制转移到最内层循环的首部
Scanner in = new Scanner(System.in);
while(sum < goal){
System.out.println(Enter a number: ");
n=in.nextInt();
if(n<0) continue;
sum += n;
}
如果 n<0, 则 continue语句越过了当前循环体的剩余部分,立刻跳到循环首部
标签
标签必须放在需要跳出的最外层循环之前,并且必须紧跟一个冒号(:
)
Scanner in = new Scanner(System.in);
int n;
read_data: //标签
while(...){
for(...){
System.out.print("Enter a number >= 0: ");
n = in.nextInt();
if(n<0) break read_data:
...
}
}
如果输入有误,通过执行带标签的 break 跳转到带标签的语句块末尾