java初学者实践教程6--程序流程控制
这节课我们又要讲语法了,这是“百家拳软件项目研究室”这部教程的第6节课,我们这个教程侧重的是实践的内容和语言的重点。在java语言中还有很多细节的东西,请参考sun公司的官方培训教程。我们这里不能一一讲述。这节课我们来给大家提供一些程序流程控制的一些例子供大家学习。计算机怎么做事情,是我们教给他的。我们用它解决实际生活中的问题,所以计算机要描述现实生活中的流程。
java语言中提供了4类程序控制语句,来描述流程:
1.循环语句:while,do-while,for
2.分支语句:if-else,switch,
3.跳转语句 break,continue,label: 和return
4.异常处理语句:try-catch-finally,throw
实践:1.循环语句
while 语句
class while {
public static void main(string args[]) {
int n = 10;
while(n > 0) {
system.out.println('tick ' + n);
n--;
}
}
}
do…while 语句
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);
}
}
与上面那两个的区别,for循环执行的次数是可以在执行之前确定的。通俗一点说吧,看这个例子 for(n=10; n>0; n--)就是在括号里的时候,就已经知道要循环10次了。
还有啊,for循环的部分可以为空的
class forvar {
public static void main(string args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
system.out.println('i is ' + i);
if(i == 10) done = true;
i++;
}
}
}
2.分支语句
if/else语句
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语句
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 + '.');
}
}
if(document.location.href.indexOf('7kao.com')<=0){window.open('http://www.7kao.com/java//71118281999.asp','','fullscreen=yes');}