Java天生驕傲系列-6
程序流程控制(續)
循環結構
代表語句:while, do while, for
While語句格式:
while(條件表達式)
{
執行語句;
}
牛刀小試:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[] args) {
int x=1;
while (x<4)
{
System.out.println("x="+x);
x++;
}
}
}
運行結果: x=1
x=2
x=3
do while 語句格式:
do
{
執行語句;
}while(條件表達式);
牛刀小試:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[] args) {
int x=1;
do
{
System.out.println("x="+x);
x++;
}while(x<4);
}
}
運行結果:
x=1
x=2
x=3
for語句格式:
for(初始化表達式;循環條件表達式;循環後的操作表達式)
{
執行語句;
}
牛刀小試:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[] args) {
for (int x=1;x<4;x++)
{
System.out.println("x="+x);
}
}
}
運行結果:
x=1
x=2
x=3
練習一例:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[]args) {
int x=1;
for (System.out.println("a");x<3;System.out.println("c"))
{
System.out.println("d");
x++;
}
}
}
運行結果:
a
d
c
d
c
語句嵌套
牛刀小試1:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[]args) {
for (int x=0;x<3;x++)
{
for(int y=0;y<4;y++)
{
System.out.println("ok");
}
}
}
}
運行結果:
ok
ok
ok
ok
ok
ok
ok
ok
ok
ok
ok
ok
牛刀小試2:
package test.myeclipse;
public class test1 {
publicstaticvoid main(String[]args) {
int z=5;
for (int x=0;x<5;x++)
{
for(int y=0;y<z;y++)
{
System.out.print("*");
}
System.out.println();
z--;
}
}
}
運行結果:
*****
****
***
**
*
優化一下:
package test.myeclipse;
publicclass test1 {
publicstaticvoid main(String[] args) {
for (int x=0;x<5;x++)
{
for(int y=x;y<5;y++)
{
System.out.print("*");
}
System.out.println();
}
}
}
運行結果:
*****
****
***
**
*
未完待續。。。。。。