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