whlie循环
循环分为三种,while循环,do while循环,for循环。
while循环是最基本的循环。
while(布尔表达式){
//循环内容}
public class Demo1 {
public static void main(String[] args) {
// 输出1-100的数
int i=0;
while(i<100){
i++;
System.out.println(i);
}
}
}
public class Demo2 {
public static void main(String[] args) {
// 输出1-100的和
int i=0;
int sum=0;
while(i<100){
i++;
sum=sum+i;
}
System.out.println(sum);
}
}
for 循环结构很重要!!
for循环是支持迭代的,最高效的一种循环结构
for循环格式如下:
for(初始化;布尔表达式;更新){
//代码语句
}
注:在idea中运行的高效语句:100.for 即可生成:
for (int i = 0; i < 100; i++) {
//其中i=0可以省去不写
}
public class forDemo4 {
public static void main(String[] args) {
//输出1-1000能被5整除的数,且每行只能输出3个
for (int i = 0; i <= 1000; i++) {
if (i%5==0) {
System.out.print(i+"\t"); \t:空格
}
if (i%(5*3)==0){
System.out.println();
}
}
}
print与println区别:
print输出不换行,println输出自动换行
public class Demo2 {
/*
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
*/
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <=i; j++) {
System.out.print(j+"*"+i+"=" +(i*j)+"\t");
}
System.out.println();
}
}
}
增强for循环:用来遍历数组和增强for循环对象
格式为:
for(声明语句:表达式)
{
//代码
}
public class Demo3 {
public static void main(String[] args) {
int[] numbers={10,20,30,40,50};
for(int x:numbers){
System.out.println(x);
}
System.out.println("------------------------------------");
for (int i = 0; i < 5; i++) {
System.out.println(numbers[i]);
}
}
}
本文详细介绍了Java中的while、do-while和for循环的结构、语法以及实际应用示例,包括计算序列、条件控制和增强for循环遍历数组。同时提到了print与println的区别。
990

被折叠的 条评论
为什么被折叠?



