Java完全手册笔记4

11 篇文章 0 订阅

-----------------控制语句


if语句,后边的语句 的大括号还是保留的好,不管是一条语句,还是多条语句。

else总是跟最近没有else配合的if配对 。


switch,对于JDK7以前的Java版本,switch的表达式必须是byte.short.int.char或枚举类型。从jdk7开始,这个表达式还可以是string类型

/*
	Use a string to control a switch statement
*/
class StringSwtich
{
	//Your program begins with a call to main().
	public static void main(String[] args) {
		String str = "two";

		switch(str)
		{
			case "one":
				System.out.println("one");
				break;
			case "two":
				System.out.println("one");
				break;
			case "three":
				System.out.println("one");
				break;
			default:
				System.out.println("no match");
				break;
		}
	}
}

switch语句有三个 重要的特征需要注意 :

1、switch语句只能进行相等性测试,这一点与if语句不同。if语句 可以对 任何类型的布尔表达式进行求值。也就是说,switch语句只查看表达式的值是否和某个case常量相匹配。

2、在同一switch语句中,两个case常量不允许具有相同的 值。当然,switch 语句与包围它外层switch语句可以 具有相同的case常量 。

3、想对于一系列嵌套的if语句,switch 语句通常效率 更高。


在Java 中,逗号只是一个分隔符。

for循环的for-each版本

一般形式如下:

for(type itr-var : collection)
    statement-block
在此,type指定了类型,itr-var指定了迭代变量的名称,迭代变量用于接受来自 集合的元素,从开始 到结束。collection指定了要遍历的集合。

需要注意的,迭代变量是“只读的”,因为 迭代变量与背后的数组 关联在一起 。对迭代 变量的一次赋值不会影响背后的数组。换句话说,不能通过迭代变量指定一个新值改变数组的内容。例如:

/*
	The for-each loop is essentially read-only
*/
class NoChange
{
	//Your program begins with a call to main().
	public static void main(String[] args) {
		int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		int sum = 0;

		//use for-each style for to display and sum the values
		for(int x : nums)
		{
			System.out.print(x + " ");
			x = x * 10;
		}
		System.out.println();

		for (int x : nums ) {
			System.out.print(x + " ");
		}
		System.out.println();
	}
}

这个例子可能不太恰当,但是这个x只是每次读取数组的值。所以类似只读。

对多位数组进行迭代。首先,把多维分解为一维,然后,迭代

/*
	Use a for-each style on a two-dimensional array
*/
class ForEach3
{
	//Your program begins with a call to main().
	public static void main(String[] args) {
		int nums[][] = new int[3][5];
		int sum = 0;

		//give nums some values
		for (int i = 0; i < 3 ; i++ ) {
			for ( int j = 0; j < 5 ; j++ ) {
				nums[i][j] = (i+1)*(j+1);
			}
		}
		//use for-each for to display and sum the values
		for (int x[] : nums ) {
			for ( int y : x ) {
				System.out.print(" " + y);
				sum  += y;
			}
			System.out.println();
		}
		System.out.println("Summation: "+sum);
	}
}

使用break语句 ,三种用途:1、终止switch语句中的语句序列。2、用途用于推出循环;3、用于goto语句的“文明”形式。

使用continue语句,终止之后的循环

return语句。显式地从方法返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值