title: 循环 date: 2020-05-17 21:37:25 tags:
while循环:
1. while结构和if很像
2. 循环要注意更新变量,防止死循环(无限循环)
3.循环的思路
while(循环条件){
循环操作 ;
}
会:可以识别循环条件、循环操作-->套语法
不会:不用循环,多写几步,观察循环条件、循环操作
例题:
public class Test5 {
public static void main(String[] args) {
//2010上网人数8000万,假设每年按百分之三十增长,问那一年人数增长到三亿
int year = 2010;
int persons = 8000;
while (persons<30000){
year ++;
persons = (int)(persons*(1+0.3));
System.out.println(year+"--"+persons);
}
System.out.println(year);
}
}
public class Test5 {
public static void main(String[] args) {
//计算100以内的偶数之和
int sum = 0;
int i = 1;
while (i<=100){
if(i % 2 == 0) {
sum = sum + i;
}
i++;
}
System.out.println(sum);
}
}
do…while循环:
public class Test5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in );
String isContinue = "";
int money = 0;
do {
System.out.println("请选择:\n1.Tshirt(100) 2.夹克(200) 3.衬衫(300)");
int choice = input.nextInt();
if(choice == 1){
System.out.println("Tshirt\t"+100);
money = money + 100;
}else if(choice == 2){
System.out.println("夹克\t"+200);
money = money + 200;
}else if(choice == 3){
System.out.println("衬衫\t"+300);
money = money + 300;
}else{
System.out.println("输入有误!!!");
}
System.out.println("是否继续?y/n");
isContinue = input.next();
}while (isContinue.equals("y"));
System.out.println(money);
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-29769.html