1.for循环
public class ForDemo1 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("HelloWorld");
}
System.out.println("--------------------------------------------");
for (int i = 1; i <=10 ; i++) {
System.out.println("HelloWorld1");
}
System.out.println("--------------------------------------------");
for (int i = 1; i <=10 ; i+=2) {
System.out.println("HelloWorld2");
}
}
}
public class ForDemo2 {
public static void main(String[] args) {
// 目标:打印输出1-100的数据,求1-100的和
for (int i = 1; i < 101; i++) {
System.out.println(i);
}
int sum = 0;
System.out.println("---------------------------------------");
for (int i = 1; i <= 100 ; i++) {
sum += i;
}
System.out.println(sum);
System.out.println("----------------------------------------");
/**
* 计算1-100之间的奇数和
*/
int sum1 = 0;
for (int i = 0; i < 100; i++) {
if (i % 2 == 1){
sum1 += i;
}
}
System.out.println(sum1);
}
}
2.while循环
// while循环
public class WhileDemo3 {
public static void main(String[] args) {
int i = 0;
while (i < 5){
System.out.println("HelloWorld");
i++;
}
}
}
3.do-while循环
public class DoWhileDemo5 {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("HelloWorld");
}while (i < 0);
// while循环中的变量可以在while外部使用
System.out.println(i);
// 而for中定义的变量只能在for循环中使用,不能在外部使用
for (int j = 0;j < 4;j++){
System.out.println(j);
}
// System.out.println(j); 报错
}
}
4.死循环
public class EndLessLoopDemo6 {
public static void main(String[] args) {
// 死循环的三种写法
/*for (; ;) {
System.out.println("HelloWorld");
}*/
/* while (true){
System.out.println("HelloWorld1");
}*/
/* do {
System.out.println("HelloWorld");
}while (true);*/
}
}
5.嵌套循环
public class LoopNestedDemo7 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("抽死你");
}
System.out.println("----------------------------------");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("*");
}
System.out.println(); // 换行
}
}
}
6.跳转关键字
public class BreakAndContinueDemo8 {
public static void main(String[] args) {
// 目标:掌握break和continue的执行
// 1.break:跳出并结束当前所在循环
for (int i = 1; i <= 5; i++) {
System.out.println("。。。");
if (i == 3) {
break;
}
}
for (int i = 0; i < 5; i++) {
System.out.println("。。。");
if (i == 2) {
break;
}
}
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println("。。。");
}
// 2.continue:提出本次循环,执行下一次循环
// 第一天干活,第二天干活,第三天休息,第四天干活
for (int i = 1; i <= 4; i++) {
if (i == 3){
System.out.println("第"+i+"天休息");
continue;
}else {
System.out.println("第"+i+"天干活");
}
}
}
}