Java 中的 System.exit() 是什麼?
此方法屬於 java.lang 包中 System 類的。它終止當前的 JVM(Java Virtual Machine)。
此方法接受代表狀態碼的整數值,它接受兩個值,0 或 1 或 -1。其中,0 表示成功終止,1 或 -1 表示不成功終止。
示例
以下程式接受使用者輸入的元素陣列並列印它。在列印過程中,如果給定的任何元素大於或等於 20,程式就會退出。
import java.util.Scanner;
public class System_Exit_Example {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created ::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array (below 20):");
for(int i=0; i<size; i++){
myArray[i] = sc.nextInt();
}
System.out.println("Printing the array .....");
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] >= 20) {
System.out.println("exit...");
System.exit(0);
} else {
System.out.println("arr2["+i+"] = " + myArray[i]);
}
}
}
}輸出
Enter the size of the array that is to be created :: 4 Enter the elements of the array (below 20): 11 12 5 20 Printing the array ..... arr2[0] = 11 arr2[1] = 12 arr2[2] = 5 exit...
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP