定義
- while(循環(huán)條件){
循環(huán)操作 // 先判斷嚷辅,再執(zhí)行
}
- 程序調(diào)試
-- 設(shè)置斷點
-- 單行運行
-- 觀察變量
- do{
循環(huán)操作 //x先執(zhí)行考榨,后判斷
}while(循環(huán)條件);
- for(參數(shù)初始化烈掠;條件判斷;更新循環(huán)變量)
{
循環(huán)操作
}
- break:改變程序控制流(中斷毒嫡,跳出整個循環(huán))
- continue:跳出本次循環(huán)
例題
- 計算100以內(nèi)(包括100)的偶數(shù)之和
int a=1;
int total=0;
while(i<=100)
{
if(a%2 == 0)
{
total=total+a;
}
a++;
}
System.out.priintln(total);
- 實現(xiàn)整數(shù)反轉(zhuǎn) 用戶輸入任意一個數(shù)字比如12345莹妒,程序輸出54321
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個數(shù)");
int num = scanner.nextInt();
while(num>0)
{
System.out.print(num % 10);
num = num / 10;
}
public class whileDemo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("輸入學(xué)生姓名");
String name = scanner.next();
int score = 0;
int total = 0;
for(int i = 1; i <= 5; i++)
{
System.out.println("請輸入"+i+"成績");
score = scanner.nextInt();
total = total + score;
}
System.out.println(name+"的平均成績是"+total/5);
}
}
public class whileDemo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("輸入學(xué)生姓名");
String name = scanner.next();
int score = 0;
int total = 0;
boolean error = false;
for(int i = 1; i <= 5; i++)
{
System.out.println("請輸入"+i+"成績");
score = scanner.nextInt();
if(score<0 || score>100)
{
error = true;
break;
}
total = total + score;
}
if(error == false)
{
System.out.println(name+"的平均成績是"+total/5);
}
else
{
System.out.println("錄入有誤");
}
}
}
public static void main(String[] args) {
int count = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入班級總?cè)藬?shù)");
int personCount = scanner.nextInt();
for(int i = 1; i <= personCount; i++)
{
System.out.println("請輸入第" + i + "次成績");
int score = scanner.nextInt();
if(score < 80)
{
continue;
}
count++;//累加成績大于等于80的次數(shù)
}
System.out.println("80分以上學(xué)生人數(shù)為" + count);
}
}