1. 程式人生 > >return和break須知

return和break須知

return

return在迴圈中表示跳出迴圈。

return 後面不能有語句,會報錯的。

正確示範:


Sacnner sc = new Scanner(System.in);

while(true){
    int num = sc.nexInt();
    if(num == -1)
        return;
}
import java.util.Scanner;


public class ReturnAndBreak {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true){
			int number = sc.nextInt();
			
			if(number == -1){
			System.out.println("跳出迴圈");
				return;
			}
			System.out.println("-------------------------------------------");
		}

	}

}

輸出結果為:

 

錯誤示範:

直接報錯!!!

 

 

break

break 跳出迴圈,後面也不可以加語句。

什麼鬼?????????????

break跳出迴圈,後面的語句不能被執行到,所以會報錯!!