循环(九)
循环(九)
while和do-whlie循环
package com.luca.structs;
public class WhileDemo1 {
public static void main(String[] args) {
//计算1到100的总和
int i = 0;
int sum = 0;
while (i<=100) {
sum += i;
i++;
}
System.out.println(sum);
//do while和while的区别:dowhile至少会执行一次语句,而while条件不成立则会立即跳出
int i2 = 0;
int sum2 = 0;
do {
sum2 += i2;
i2++;
} while (i2<=100);
System.out.println(sum2);
}
}
for循环
package com.luca.structs;
public class ForDemo1 {
public static void main(String[] args) {
//使用for输出1到100的和
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
System.out.println("================");
//输出1到100中的奇数和与偶数和
int oddsum = 0;
int evensum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
evensum += i;
} else {
oddsum += i;
}
}
System.out.println("奇数和是:" + oddsum);
System.out.println("偶数和是:" + evensum);
System.out.println("================");
//输出1-100中所有5的倍数,并且三个为一行显示
for (int i = 1; i <= 100; i++) {
if (i % 5 == 0) {
System.out.print(i + " ");
}
if (i % 15 == 0) {
System.out.println();
}
}
System.out.println();
System.out.println("================");
//打印九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) { //注意这里的j<=i
System.out.printf("%d*%d=%d ", i, j, i * j);
}
System.out.println();
}
System.out.println("================");
//增强型for循环
int[] m = {1, 2, 3, 4, 5}; //定义一个数组,相当于python的list
for (int x: m) {
System.out.print(x+"\t"); //这里的\t需要用双引号括起来,用单引号的话会有问题
}
}
}
上面for循环输入结果如下:
使用for循环打印一个三角形
现在打印的三角形比较丑,是将打印拆分成三个部分拼起来
package com.luca.structs;
public class ForDemo02 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
//打印最左边的空白三角
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
//打印中间的半个三角形
for (int j = 1; j<=i; j++) {
System.out.print("*");
}
//打印右边的半个三角形
for (int j = 5; j > (5-i); j--) {
System.out.print("*");
}
System.out.println();
}
}
}
Break和Continue
Break:跳出循环结构
package com.luca.structs;
public class BreakDemo {
public static void main(String[] args) {
int i = 0;
while (i<10) {
i++;
if (i==5) {
break; //如果i=5,会跳出循环结构
}
System.out.println(i);
}
System.out.println("It's over.");
}
}
Continue:跳出本次循环
package com.luca.structs;
public class ContinueDemo {
public static void main(String[] args) {
//break continue goto/label
int i = 0;
while (i < 10) {
i++;
if (i==5){
continue; //如果i=5,则跳出本次循环,继续下一轮循环
}
System.out.println(i);
}
}
}