第五章 循环
5.2 while循环
1.while循环的语法如下:
while(循环继续条件){
//循环体
语句(组);
}
2.程序:提示用户为两个个位数相加的问题给出答案
package com.chapter5; import java.util.Scanner; public class RepeatAdditionQuiz { /**
* 提示用户为两个个位数相加的问题给出答案
*/ public static void main(String[] args) { int number1=(int) (Math.random()*10);
int number2=(int) (Math.random()*10); Scanner input=new Scanner(System.in); System.out.println("请输入:"+number1+" + "+number2+" 的结果");
int answer=input.nextInt(); while(number1+number2!=answer){
System.out.println("答案错误,请重新输入 "+number1+" + "+number2+" 的结果");
answer=input.nextInt();
} System.out.println("正确答案是:"+answer); } }
3.程序:猜数字
package com.chapter5; import java.util.Scanner; public class GuessNumber { /**
* 猜数字
*/ public static void main(String[] args) { int number=(int) (Math.random()*101); Scanner input=new Scanner(System.in);
System.out.println("猜测的数字在0-100之间包含0和100"); int guess=-1;
while(guess!=number){
System.out.println("输入您猜测的数字");
guess=input.nextInt(); if(guess==number){
System.out.println("猜测正确!");
}else if(guess>number){
System.out.println("您猜测的数字大了!");
}else{
System.out.println("您猜测的数字小了!");
}
}
} }
5.3 do-while循环
1.首先执行循环体,然后计算循环继续条件。如果计算结果为true,则重复执行循环体;如果为false,则终止do-while循环。
2.程序:TestDoWhile
package com.chapter5; import java.util.Scanner; public class TestDoWhile { public static void main(String[] args) { int data;
int sum=0; Scanner input=new Scanner(System.in); do{
System.out.print("输入一个整数(如果是0输入结束):");//Enter an integer(the input ends if it is 0)
data=input.nextInt();
sum+=data;
}while(data!=0); System.out.println("总和为:"+sum); } }
5.4 for循环
1.语法:
for(初始操作;循环继续条件;每次迭代后的操作){
//循环体
语句(组);
}
5.5 采用哪种循环
while循环和for循环都称为前测循环(pretest loop),因为继续条件是在循环体执行之前检测的,do-while循环被称为后测循环(posttest loop),因为循环条件是在循环体执行之后检测的。
5.6 嵌套循环
1.程序:乘法表
package com.chapter5; public class MultiplicationTable { /**
* 乘法表
*/ public static void main(String[] args) { System.out.println("Multiplication table");
System.out.print(" "); for(int i=1;i<=9;i++){
System.out.print(" "+i);
}
System.out.println("\n----------------------------------------");
for(int i=1;i<=9;i++){
System.out.print(i+"|");
for(int j=1;j<=9;j++){
System.out.printf("%4d",i*j);
}
System.out.println();
} } }
5.8 示例学习
求最大公约数
package com.chapter5; import java.util.Scanner; public class GreatestCommonDivisor { /**
* 求最大公约数
*/ public static void main(String[] args) { Scanner input=new Scanner(System.in); int gcd=1;//1是一个公约数,但不是最大公约数
int k=2; System.out.println("请输入第一个整数:");
int number1=input.nextInt();
System.out.println("请输入第二个整数:");
int number2=input.nextInt(); while(k<=number1 && k<=number2){
if(number1%k==0 && number2%k==0){
gcd=k;
}
k++;
}
System.out.println(number1+" 和 "+number2+" 的最大公约数为:"+gcd);
} }