- While循环: while(boolean){代码块} 当boolean=true 则执行代码块内容 反之跳出循环
@Test
//输出三遍我爱你
public void test00(){
int i = 0;
while (i<3){
i++;
System.out.println("我爱你");
}
System.out.println("over");
}
- Example:输出0到10间且不包含10的所有偶数
@Test
public void test02(){
int i = 0;
while (i<10){
if (i % 2 == 0){
System.out.println(i);
}
i++;
}
}
- Break :break会跳出循环 也叫结束循环
@Test
public void test03(){
//需求:A可以输出5次 但第3次被B打断 且后面不会输出
int i = 0;
while (i<5){
i++;
if (i == 3){
System.out.println("第三刀被B打断");
break;
}
else {
System.out.println("A输出的第"+i+"刀");
}
}
}
- Continue:可以跳过本次循环但循环继续 现在需求同上,但可以输出第4次和第五次
@Test
public void test04(){
int i = 0;
while (i<5){
i++;
if (i == 3){
System.out.println("第三次被B打断");
continue;
}
else {
System.out.println("A输出的第"+i+"刀");
}
}
}
- For循环: 用for循环写出0到10内所有偶数 不包含10
@Test
public void test05(){
for (int i = 0; i < 9; i++) {
if (i % 2 == 0){
System.out.println(i);
}
}
}
- 双层for循环
@Test
public void test06(){
for (int i = 0; i <3 ; i++) {
for (int j = 0; j <3 ; j++) {
System.out.println("第" + (i + 1) + "天" + "\t" + "第" + (j + 1) + "次");
}
}
}
- 九九乘法表
@Test
public void test07(){
for (int i = 0; i <9 ; i++) {
for (int j = 0; j <i + 1 ; j++) {
System.out.print((j + 1) + "*" + (i + 1) + "=" + (j + 1)*(i + 1) + "\t");
}System.out.println("");
}
}