[定稿]Java循环选择控制语句
Java循环选择控制语句
算法
分支语句
循环语句
跳转语句
算法的特性:
1.有穷性
2.确定性
3.由零个或多个输入 4.有一个或多个输出 5.有效性
例:求a,b,c中的最大值
package test;
public class cf
{
public static void main(String[] args)
{
int a=5;
int b=7;
int c=12;
if(a>b)
{
if(a>c)
System.out.println("a="+a);
else
System.out.println("c="+c);
}
else
if(ai)
{
break;
}
System.out.printf("%d*%d=%d ",i,j,i*j);
}
System.out.printf("\n");
}
}
}
输出结果:
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
跳转语句
1.break跳转语句
例:使用break语句结束循环
package test;
public class cf
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
if(i==5)
{
break;
}
System.out.printf("%d\n",i);
i++;
}
System.out.println("输出结束了");
}
}
输出结果:
1
2
3
4
输出结束了
2.continue语句
例:
package test;
public class cf
{
public static void main(String[] args)
{
int i=0;
while(i<=10)
{
i++;
if(i==5)
{
continue;
}
System.out.printf("%d\n",i);
}
System.out.println("输出结束了");
}
}
输出结果:
1
2
3
4
6
7
8
9
10
11
输出结束了
3.return语句 例:求1~10之间2的倍数 package test;
public class cf {
public static void main(String[] args)
{
for(int n=10;n>0;n--)
{
if(n%2==0)
{
System.out.printf("%d ",n);
}
else
continue;
}
}
}
输出结果:
10 8 6 4 2
第二种方法:
package test;
public class cf
{
public static void main(String[] args)
{
int n=10;
for(int i=1;i<=n;i++)
{
if(makeCondition(i))
{
System.out.print(i+" ");
}
}
return;
}
public static boolean makeCondition(int j)
{
if(j%2==0)
{
return true;
}
return false;
}
}
输出结果:
2 4 6 8 10
Java程序实例
求1~100之间的所有素数,要求10个数一行
package test;
public class cf
{
public static void main(String[] args)
{
int m,k,i,n=0;
for(m=2;m<=100;m=m+1)
{
k=(int)java.lang.Math.sqrt(m);
for(i=2;ik+1)
{
System.out.print(m);
System.out.print(" ");
n++;
}
if(n%10==0)
{
System.out.println("");
}
}
}
}