[Java] 5 Fully understand the control process of java

1. Block scope

块(即复合语句)Refers to a statement consisting of several Java statements, enclosed in a pair of curly braces.
块确定了变量的作用域。
一个块可以嵌套在另一个块中. Below is a block nested within the main method block.

public static void main(String[] args){
    
    
	int n;
	...
	{
    
    
		int k;
		...
	}//k is only defind up to here	
}

However, 不能在嵌套的两个块中声明同名的变量.

public static void main(String[] args){
    
    
	int n;
	...
	{
    
    
		int k;
		int n;  //ERROR---can't redefine n in inner block
		...
	}//k is only defind up to here	
}

2. Conditional statement

In Java, the form of a conditional statement is if (condition) statement, where the conditions must be enclosed in parentheses.

  • If you need to execute multiple statements while a certain condition is true. In this case, you can use the block statement
if(yourSales >= target)
{
    
    
	performance = "Satisfactory";
	bonus = 100;
}
//当 yourSales大于或等于target 时,将执行大括号中的所有语句
  • Flowchart of the if statement
Created with Raphaël 2.2.0 开始 yourSales >= target? performance ="Satisfactory" bonus = 100 结束 yes no
  • Flow chart of if/else statement
Created with Raphaël 2.2.0 开始 yourSales >= target? performance ="Satisfactory" bonus = 100+0.01* (yourSales -target) 结束 performance ="Unsatisfactory" bonus = 0 yes no

3. Iteration statement

  • while, do-whileand forused to control loops, they are also called iteration statements (iteration statement).
  • An iteration statement executes repeatedly until the controlling Boolean expression evaluates to false.

3.1 while statement

  • Format:while(condition) statement
  • If the value of the loop condition is false at the beginning, the while loop will not execute once
  • Flowchart of the while statement
Created with Raphaël 2.2.0 开始 确认? 操作1 操作2 输出 结束 yes no
  • while循环statement checks the loop condition at the top. Therefore,
    the code in the loop body has 可能一次都不执行. If you want 循环体至少执行一次, you need to make do-whilethe loop put the check last.

3.2 do-while statement

  • Format:do statement while(condition);
  • This loop statement first executes a statement (usually a statement block), and then checks the loop condition. If true, execute the statement repeatedly, then check the loop condition again, and so on.
  • Flowchart of the do-while statement
Created with Raphaël 2.2.0 开始 操作1 输入 确认? 结束 yes no

3.3 for statement

  • Format:for(initialization;boolean-expression;step) statement
    • Initialization, Boolean-expression and step can all be empty
  • 每次迭代前会测试布尔表达式。只要结果是false,就不再循环,而是执行跟在foi循环后面的语句。每次循环结束,都会执行一次步进
  • for语句的流程图
Created with Raphaël 2.2.0 开始 操作1 确认? 输出操作 操作2 结束循环 yes no
  • 当在for语句的初始化部分中声明了一个变量之后,这个变量的作用域就扩展到这个for循环体的末尾。
for(int i= 1;i <= 10;i++)
{
    
    
	...
}
//i no longer defined here
  • 特别指出,如果在for语句内部定义一个变量,这个变量就不能在循环体之外使用。因此,如果希望在for循环体之外使用循环计数器的最终值,就要确保这个变量在循环之外声明!
int i;
for(i= 1;i <= 10;i++)
{
    
    
	...
}
//i is still defined here
  • 可以在不同的for循环中定义同名的变量
for(int i= 1;i <= 10;i++)
{
    
    
	...
}
for(int i= 11;i <= 20;i++) 
//OK to define another variable named i
{
    
    
	...
}
  • for 循环语句其实可以理解为while循环的一种简化形式:
for(i= 1;i > 10;i--)
{
    
    
	...
}
int i = 10;
while(i > 0){
    
    
	i--;
}

3.4 for-in语法

  • Java 5引入了一种更加简洁的for语法,可以用于数组和容器,有时候叫作"増强的for" ( enhanced for )。大部分文档中直接将其称为foreach语法,但Java 8里又增加了一个我们经常使用的forEach()方法。这样的术语使用起来容易混淆,在《On Java》中叫做for-in语法
  • for-in语句会自动为你生成每一项元素,这样你不需要创建int变量来对这个元素构成的序列进行计数。
import java.util.*;
public class ForInFloat{
    
    
	public static void main(String[] args){
    
    
		float[] f = new float[10];
		for(int i = 0;i < 10;i++) //旧式的for循环
			f[i] = i;
		for(float x : f)  //for-in语法
			System.out.println(x);
	}
}
  • for(float x : f)这条语句定义了一个float类型的变x,然后会将数组f里的每一个元素按顺序赋给x
  • 任何返回了数组的方法都可以使用for-in
    • 例如,String类有一个toCharArray方法,它返回了一个char数组,因此你可以很容易地迭代字符串里的所有字符:
public class ForInString{
    
    
	public static void main(String[] args){
    
    
		for(char c : "An African Swallow".toCharArray())
			System.out.println(c + " ");
  • 许多for语句会在一个整数值序列中步进,如for(int i = 0;i < 10;i++),对于这些语句,for-in语法不起作用,因为你需要先创建一个int数组。

4.中断控制流程的语句

4.1 return

  • 用途: 1. 可以指定一个方法的返回值(如果不存在就返回void ); 2. 导致当前的方法退出,并且返回这个值。
  • 如果在一个返回了 void的方法中没有return语句,那么该方法的结尾处会有一个隐含的return,所以方法里并不一定会有一个return 句。
  • 如果你的方法声明了它将返回一个非void的值,那就必须确保每一条代码路径都会返回一个值

4.2 break和continue

  • 在任何迭代语句的主体部分,都可以使用break和continue来控制循环流程。
    • break会直接退出循环,不再执行循环里的剩余语句。
    • continue则会停止执行当前的迭代,然后退回循环开始位置执行下一次迭代。

4.2.1 不带标签的break语句

while(y <= 100){
    
    
	b += p;
	double i = b * 2.5;
	b += i;
	if(b >= 10) break;  // <--break语句
	years++;
}
  • 在循环开始时,如果y>100,或者在循环体中b≥10,则退出循环语句。

4.2.2 带标签的break语句

  • 带标签的break语句,用于跳出多重嵌套的循环语句。
  • 请注意,标签必须放在希望跳出的最外层循环之前,并且必须紧跟一个冒号
Scanner in = new Scanner(System.in);
int n;
read_data:  //<--标签,带冒号
while(...){
    
    
	...
	for(...){
    
    
		...
		if(...)
			break read_data;
			//执行带标签的break会跳转到带标签的语句块末尾
	}
}
//break之后,跳到此处

4.2.3 continue语句

  • continue语句将控制转移到最内层循环的首部。
Scanner in = new Scanner(System.in);
while(...){
    
    
	...
	
	int n = in.nextInt();
	if(n < 0) continue;
	//如果n<0,则continue语句越过了当前
	//循环体的剩余部分,立刻跳到循环首部。
	
	...
	
}
  • 如果将continue语句用于for循环中,就可以跳到for循环的“更新”部分
Scanner in = new Scanner(System.in);
for(count = 1;count <= 100;count++){
    
    
	...

	int n = in.nextInt();
	if(n < 0) continue;
	//如果n<0,则continue 语句将跳到count++语句
	...
}

4.3 goto()

  • 尽管goto是Java中的一个保留字,但Java中并没有使用它——Java没有goto
  • Java也有一些类似于跳转的操作,这些操作与break和continue关键字有关,它们不是跳转,而只是中断循环的一种方式。之所以和goto一起讨论,是因为它们使用了相同的机制:标签。
  • 标签:标签是以冒号结尾的标识符,形如 label:
    • 在Java中,放置标签的唯一地方是正好在迭代语句之前:不要在标签和迭代之间播入任何语句
label:
outer-iteration{
    
    
	inner-iteration{
    
    
		//...     //[1]
		break;
		//...     //[2]
		continue;
		//...     //[3]
		continue label;
		//...     //[4]
		break label;
	}
}
  • [1]这里的break中断内部迭代,回到外部迭代
  • [2] 这里的continue中断当前执行,回到内部迭代的开始位置
  • [3] 这里的continue label会同时中断内部迭代以及外部迭代,直接跳到label处,然后它实际上会重新进入外部迭代开始继续执行。
  • [4] 这里的break label也会中断所有迭代,跳回到labell处,不过它并不会重新进入外部迭代。它实际是完全跳出了两个迭代
  • 在Java里使用标签的唯一理由就是你用到了嵌套循环,而且你需要使用break或continue来跳出多层的嵌套。

5.多重选择:switch语句

  • 处理多个选项时,使用if-else结构显得有些笨拙,Java 有一个与C/C++完全一样的switch 语句
switch(integral-selector){
    
    
	case integral-value1 : statement; break;
	case integral-value2 : statement; break;
	case integral-value3 : statement; break;
	case integral-value4 : statement; break;
	case integral-value5 : statement; break;
	//...
	default:statement;
}
  • 整数选择器(integral-selector)是一个能生成整数值的表达式.switch将这个表达式的结果与每个整数值(integral-value )相比较:
    • 如果发现相等,就执行对应的语句(单条语句或多条语句,不要求使用花括号包围)
    • 若没有发现相等,就执行默认(default)语句
  • 毎个case都用一个break结尾,它会让执行流程跳到switch主体的末尾
    • break是可选的。如果省略后面的case语句也会被执行,直到遇到一个break
  • 最后的default语句里没有break,这是因为default语句执行完的地方,本来就是bieak跳转的目的地
  • switch语句的流程图
Created with Raphaël 2.2.0 开始 choice = 1 操作... 结束 choice = 2 操作... choice = 3 操作... choice = 4 操作... (default) yes no yes no yes no yes no

在Java 7之前,switch的选择器执行结果必须是整数值,比如int或char;Java 7的switch选择器不但可以使用整数值,还添加了使用字符串的能力

Guess you like

Origin blog.csdn.net/qq_40332045/article/details/129579844