一、while语句
while语句格式如下:
while(条件表达式)
循环体
首先检查表达式的值是否位真,若为真,则执行循环体,然后继续判断是否继续循环,直到条件表达式的值为假,执行后续语句。“先判断,后执行”。
【例1】在3位数中找出所有水仙花数,水仙花数的条件该数等于其各位数字的立方和。
public class Test3 {
public static void main(String args[]) {
int i,j,k,n=100,m=1;
while(n<1000) {
i=n/100;
j=(n-i*100)/10;
k=n%10;
if(Math.pow(i, 3)+Math.pow(j, 3)+Math.pow(k, 3)==n)
System.out.println("找到第"+ m++ +"个水仙花数:"+n);
n++;
}
}
}
【 注】Math类的一个静态方法pow()来计算某位数字的立方。
【例2】从键盘输入一个长整数,求其各位数字之和。
import javax.swing.JOptionPane;
public class Test3 {
public static void main(String args[]) {
long n,m=0;
n=Long.parseLong(JOptionPane.showInputDialog("输入整数"));
long a=n;
while(a>0) {
m+=a%10;
a=a/10;
}
System.out.print(n+"的各位数字之和="+m);
}
}
二、do...while语句
“先执行,后判断”,格式如下:
do{
循环体
}while(循环条件);
三、for语句
for语句一般用于事先能够确定循环次数的场合,其格式如下:
for(控制变量设定初值;循环条件;迭代部分)
循环体
【例1】求1+1/2+1/3+1/4+...+1/100的值。
public class Test3 {
public static void main(String args[]) {
double sum=1;
for(int k=2;k<=100;k++)
sum=sum+1.0/k;
System.out.println("1+1/2+1/3+1/4+...+1/100="+sum);
}
}
【例2】利用 随机函数产生10道两位数的加法测试题,根据用户的解答输入计算得分。
import javax.swing.*;
public class Test4 {
public static void main(String args[]) {
int score=0;
for(int i=0;i<10;i++) {
int a=10+(int)(90*Math.random());
int b=10+(int)(90*Math.random());
String s=JOptionPane.showInputDialog(a+"+"+b+"=?");
int ans=Integer.parseInt(s);
if(a+b==ans)
score=score+10;
}
JOptionPane.showMessageDialog(null, "your score="+score);
}
}
循环嵌套
【例】找出3~50中所有素数,按每行5个数输出。
import javax.swing.*;
public class Test4 {
public static void main(String args[]) {
int m=0;
for(int n=3;n<=50;n++) {
boolean f=true;
int k=2;
while(f&&k<=(n-1)) {
if(n%k==0)
f=false;
k++;
}
if(f) {
System.out.print("\t"+n);
m++;
if(m%5==0)
System.out.println();
}
}
}
}