Java—基本语句

条件语句(分支语句)

  • if条件语句
public class TestIF {
	public static void main(String[] args) {
		int i = 20;
		if(i < 20) {
			System.out.println("<20");
		} else if (i < 40) {
			System.out.println("<40");
		} else if (i < 60) {
			System.out.println("i < 60");
		} else
			System.out.println("i <= 60");
		//只有一句需要执行时可以省略{}
		//但是只执行一句
	}
}
  • switch语句
public class TestSwitch {
	public static void main(String[] args) {
		int i = 18;
		switch(i) {
			case 8:
			System.out.println("A");
			break;
			case 3:
			System.out.println("B");
			break;
			case 2:
			System.out.println("C");
			break;
			default:
			System.out.println("error");
		}
	}
}
/*多个case合并:
			case 8:
			case 3:
			case 2:
			System.out.println("AA");
			break;

*/

小心case穿透,使用break语句。
多个case可以合并到一起。
java中switch语句只能探测int类型值(char,byte,short可以转换为int)。

循环语句

  • for循环语句
    在这里插入图片描述
//for 语句形式
/*
	for(表达式1;表达式2;表达式3) {
		语句;
		...;
		语句;
	}
*/

例:计算1+3+5+…+99?

public class TestOddSum {
	public static void main(String[] args) {
		int result = 0;
		for (int i=1;i<100;i+=2) {
			result += i;
		}
		System.out.println("result=" + result);
	}
}
  • while,do while语句
    在这里插入图片描述
public class TestWhile {
	public static void main(String[] args) {
		int i = 0;
		while(i < 10) {
			System.out.println(i);
			i++;
		}						//0~9		
		
		i = 0;					//int i = 0不可
		do {
			i++;
			System.out.println(i);
		} while(i < 10);		//1~10不能忘记分号
		
		i = 0; 
		do {
			System.out.println(i);
			i++;
		} while(i < 10);		//0~9
	}
}

break,continue语句

  • break语句:终止某个语句块的执行,用在循环语句体中可强制退出循环。(终止break所在的一层循环
public class TestBreak {
	public static void main(String[] args) {
		int stop = 4;
		for(int i=1;i<=10;i++) {
			//当i等于4时退出循环
			if(i == stop) break;
			 System.out.println("i=" + i);
		}
	}
}
  • continue语句:用在循环语句体中用于终止某次循环过程,跳过循环体中continue下面未执行的循环,开始下一次循环。
public class TestContinue {
	public static void main(String[] args) {
		int skip = 4;
		for(int i = 1;i<=5;i++) {
			//当i等于skip时,跳过当次循环
			if(i == skip) continue;			//if(i == skip);continue;
			System.out.println("i=" + i);	//System.out.println(i);永远不能执行到此句
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值