java中的控制语句

一、选择结构

if else

public class HelloWorld {
    public static void main(String []args) {
		boolean k=true;
		if(k){
			System.out.println("true");
		}else{
			System.out.println("false");
		}
		
		int u=6;
		if(u<5){
			System.out.println("u < 5");
		}else if(u<10){
			System.out.println("5 < u < 10");
		}else{
			System.out.println(u);
		}
    }
}

JAVA在调试-点击马上尝试

switch case

单变量多值判断。

public class HelloWorld {
    public static void main(String []args) {
		int u=6;
		switch(u){
		case 1:
			System.out.println("u = 1");
			break;
		case 2:
			System.out.println("u = 2");
			break;
		case 3:
			System.out.println("u = 3");
			break;
		default:
			System.out.println("u = other");
		}
    }
}

二、循环结构

  • break; 结束整个循环。
  • continue; 跳过本次循环,进入下一次循环。

while

满足条件后跳出。注意不要搞成死循环了。
do-while 是先执行在判断,实际工作中使用较少。

public class HelloWorld {
    public static void main(String []args) {
		int k = 0;
		int c = 0;
		//求1到100的累加
		while(k<=100){
			c+=k++;
		}
		System.out.println(c); //5050
    }
}

for

是在while的基础上规范了写法,实际开发中比while还常用。

public class Main {
    public static void main(String []args) {
		int c = 0;
		//求1到100的累加
		for(int k=0;k<=100;k++){
			c+=k;
		}
		System.out.println(c); //5050
    }
}
public class Main {
    public static void main(String []args) {
		//打印九九乘法表
		for(int a=1;a<=9;a++){
			for(int b=1;b<=a;b++){
				System.out.print(""+a+"*"+b+"="+(a*b)+"\t");
			}
			System.out.println("");
		}
    }
}
public class Main {
    public static void main(String []args) {
		//打印九九乘法表,不显示乘数相等的内容,可以使用标签跳转功能。
		tiao:for(int a=1;a<=9;a++){
			for(int b=1;b<=a;b++){
				if(a==b){
					System.out.println("");
					continue tiao; //跳转到tiao标签处
				}
				System.out.print(""+a+"*"+b+"="+(a*b)+"\t");
			}
			
		}
    }
}

for-each

用于读取数组内容。

public class Main {
    public static void main(String []args) {
		String[] strs = {"呵呵呵","哈哈哈","嘻嘻嘻"};
		for(String str: strs){
			System.out.println(str);
		}
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值