此方法属于java.lang包的System类。它终止当前JVM(Ĵ AVA V irtual中号achine)。
此方法接受代表状态码的整数值,它接受两个值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...