|
JAVA程序员必读:基础篇(3)语言基础
|
|
编译:ZSC/太平洋网络学院
|
|
|
语言基础
3.4.1 while和do-while语句
你可以使用while语句当条件保持为true的时候,持续执行语句块。While语句的通常语法为:
while (expression) {
statement
}
首先,while语句执行表达式,它将返回一个boolean数(true或者false)。如果表达式返回true,while语句执行相应的语句。While语句继续测试表达式并执行块代码直到表达式返回false。
下面给出一个例程WhileDemo,它使用while语句来浏览字符串的各个字符并复制字符串直到程序找到字符g为止:
public class WhileDemo {
public static void main(String[] args) {
String copyFromMe = "Copy this string until you
" +
"encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();
int i = 0;
char c = copyFromMe.charAt(i);
while (c != 'g') {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);
}
}
最后一行打印出来的数值为:Copy this strin.
[上一页]
[下一页]
|