java--程序流程控制

java语言中提供了4类程序控制语句,来描述流程:

    1.循环语句:while,do-while,for

    2.分支语句:if-else,switch,

    3.跳转语句 break,continue,label: 和return

    4.异常处理语句:try-catch-finally,throw

1.循环语句

    while 语句

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
class While {
public static void main(String args[]) {
int n = 10
while (n > 0 ) {
System.out.println(
" tick " + n);
n
--
}
}
}

do…while 语句

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
class DoWhile {
public static void main(String args[]) {
int n = 10
do {
System.out.println(
" tick " + n);
n
--
}
while (n > 0 );
}
}

二者区别,do…while至少循环一次,而while的表达式要是为flase的话可以一次也不循环。再通俗一点,do…while就算是括号里的是flase,人家最少也能do一次。

    for语句

 
  
class ForTick {
public static void main(String args[]) {
int n;
for (n = 10 ; n > 0 ; n --
System.out.println(
" tick " + n);
}
}

2.分支语句

    if/else语句

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
class IfElse {
public static void main(String args[]) {
int month = 4 // April
String season;
if (month == 12 || month == 1 || month == 2
season
= " Winter "
else if (month == 3 || month == 4 || month == 5
season
= " Spring "
else if (month == 6 || month == 7 || month == 8
season
= " Summer "
else if (month == 9 || month == 10 || month == 11
season
= " Autumn "
else
season
= " Bogus Month "
System.out.println(
" April is in the " + season + " . " );
}
}

// 这段程序输出:

// April is in the Spring.

// 注意 “||”是或运算

switch语句

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
class Switch {
public static void main(String args[]) {
int month = 4
String season;
switch (month) {
case 12
case 1
case 2
season
= " Winter "
break
case 3
case 4
case 5
season
= " Spring "
break
case 6
case 7
case 8
season
= " Summer "
break
case 9
case 10
case 11
season
= " Autumn "
break
default
season
= " Bogus Month "
}
System.out.println(
" April is in the " + season + " . " );
}
}

 

转载于:https://www.cnblogs.com/lovening/archive/2010/08/02/1790630.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值