今天学习的是判断与循环,总结如下:
一、switch循环很好理解,基本语句就是
switch(case){
case 1:
语句1
break;
case 2:
语句2
break;
default:
语句3
}
case=1,执行语句1和break
case=2,执行语句2和break
case等于其他值,执行语句3,然后跳出循环。
需要注意的是每一个case后面的语句结束后都要加一个break跳出循环,如果不需要跳出循环则不用考虑。
如果case后面没有break的话,程序会一直往下走,直到遇到第一个break使程序跳出循环。
例如:
public class test2_1 {
public static void main (String[] args){
Scanner in=new Scanner(System.in);
System.out.print("请输入一个type值:");
int type=in.nextInt();
System.out.println(type);
switch(type){
case 1:
case 2:
System.out.print("你好");
break;
case 3:
System.out.print("下午好");
case 4:
System.out.print("再见");
break;
default:
System.out.print("什么?");
}
}
}
通过控制台输入:
输入1,输出“你好”//case 1没有break,向下执行case 2,输出“你好”,break跳出循环
输入2,输出“你好”//输出“你好”,break跳出循环
输入3,输出“下午好再见”//case 3,输出“下午好”,没有break,向下执行case 4,输出“再见”,break跳出循环
输入4,输出“再见”//输出“再见”,break跳出循环
输入5,会输出“什么?”
二、while循环while循环就是当某某条件为真true时,执行循环体。它的功能之一是可以使某个功能一直实现下去,而不需要每次都重新运行。例如下面的售票功能:
public class test2_2 {
public static void main(String[] args){
int add=0;
while(true) {
System.out.println("请输入金额:");
Scanner in = new Scanner(System.in);
int amount = in.nextInt();
add=add+amount;
if (add >=10) {
System.out.println("******************");
System.out.println("* 铁路专线 *");
System.out.println("* 无指定座位票 *");
System.out.println("* 票价:10元 *");
System.out.println("******************");
System.out.println("找零:" + (add - 10));
add=0;
}
}
}
}
在没有增加while循环时,每一次运行程序都只能售一次票,而且不能进行累加。
增加while循环之后,多个用户可以进行买票,并且一位用户可以多次输入金额,只要输入的总金额达到十元就可以出票,通过增加while循环使功能更加完善了。
三、do-while循环基本语句就是:
do
{
循环体
}while(约束条件);
它与while循环的区别就是,先执行一次循环体中的内容,再测试while是否为真true,真则进入循环,否则不再循环继续向下进行。不论条件是否满足,do-while至少进行一次循环。经常用于某些边界值很特殊的情况或者某个值的获取需要在第一次循环中得到。
例如计数问题:用户通过键盘输入一个值,程序计算用户输入值的位数。
public class test2_3 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int number = in.nextInt();
int count=0;
// while(number>0){
// number=number/10;
// count++;
// }
do {
number=number/10;
count++;
}while(number>0);
System.out.print(count);
}
}
如果使用while循环,当用户输入0,不满足循环条件,一次都没有循环,程序会输出0。这显然是错误的,正确的程序应该输出1。
当使用do-while循环,程序至少执行一次,并且对其他的输入情况得到的值也是正确的。
求平均数的程序:
public class test2_4 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int number;
int count=0;
int sum=0;
// number=in.nextInt();
// while(number!=-1)
// {
// sum=sum+number;
// count=count+1;
// number=in.nextInt();
// }
do {
number=in.nextInt();
if(number!=-1) {
sum = sum + number;
count = count + 1;
}
}while(number!=-1);
if(count>0) {
System.out.print("平均数=" + (double) sum / count);
}
}
}
如果使用while语句,首先要在循环体外得到一个用户输入值,然后判断是否进入循环体,进入循环体后,又需要一条语句获取用户输入的值。
使用do-while语句,因为至少执行一次,所以可以把循环体外的这条语句放到循环体中,这样就减少了一条看似重复的代码,但是第一次获取值后也要判断是否等于-1,而这与while()中的判断语句也有重复,并且循环体中的语句会执行多次,这种代码重复的代价似乎比第一种更高,因此两种循环方法都有各自的特点,要视情况而定。



