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...

更新於: 30-7 月-2019

258 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告