Java day-05
阿新 • • 發佈:2017-08-05
cnblogs main println pack public mage 格式 print tca
循環結構:while dowhile
while語法格式:
while(條件表達式)
{
執行語句;
}
int x = 1; while (x<3){ System.out.println("x=" +x); x++; } int a = 1;
練習:sum=1+100=5050
int i=1,sum=0; while(i<=100) { sum=sum+i; i++; System.out.println("sum="+sum);//輸出語句寫在循環體內 }
輸出每次疊加的過程
int i=1,sum=0; while(i<=100) { sum=sum+i; i++; } System.out.println("sum="+sum);//循環體外
運行結果:
package cn.itcast.test; public class While_Demo {// 100以內能被6整除的次數
public static void main(String[] args) { int i=1; int count=0; while(i<=100) { if(i%6==0) count++; i++; } System.out.println("conut="+count); } }
運行結果:
do while語法格式:
do
{
執行語句;
}while(條件表達式);
do { System.out.println("a="+a); a++; }while(a<3);
package cn.itcast.test; public class DoWhile_Demo { public static void main(String[] args) { int i=1,sum=0; do { sum=sum+i; i++; }while(i<=100);//分號切記莫忘 System.out.println("sum="+sum); } }
Java day-05