在 Java 中使用 System.exit() 方法
本教程介绍了 Java 中的 System.exit()
方法的作用。
System
是 Java 中的一个类,它提供了几种实用方法来处理与系统相关的任务,例如 exit()
方法用于停止当前执行和 JVM 并将控制权退出给程序。我们可以在我们的代码中使用这个方法来退出当前流程。
此方法的一般语法如下所示。
public static void exit (int status)
它终止当前正在运行的 Java 虚拟机。
它采用一个整数参数作为状态码。按照惯例,非零状态码表示异常终止。
此方法调用类 Runtime
中的 exit
方法。此方法永远不会正常返回。在内部,它类似于下面的代码。
Runtime.getRuntime().exit(n)
如果存在安全管理器,则此方法抛出 SecurityException
,并且其 checkExit
方法不允许以指定状态退出。
Java 中的 System.exit()
方法
此示例使用 exit()
方法在任何列表元素大于 50
时退出程序。如果元素小于 50
,则打印最大元素,但如果任何元素大于 50
,则退出并打印再见到控制台。
请参见下面的示例。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SimpleTesting{
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
list.add(23);
list.add(32);
list.add(33);
System.out.println(list);
Integer result = getMax(list);
System.out.println("result "+result);
list.add(80);
result = getMax(list);
System.out.println("result "+result);
}
public static Integer getMax(List<Integer> list) {
if(Collections.max(list)>50) {
System.out.println("Bye");
System.exit(1);
return Collections.max(list);
}
return Collections.max(list);
}
}
输出:
[23, 32, 33]
result 33
Bye
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中执行 SQL 查询
发布时间:2024/04/24 浏览次数:1195 分类:Python
-
本教程演示了在 Python 中对 Pandas DataFrame 执行 SQL 查询。
在 Pandas 中使用 stack() 和 unstack() 函数重塑 DataFrame
发布时间:2024/04/24 浏览次数:1289 分类:Python
-
本文讨论了 Pandas 中 stack() 和 unstack() 函数的使用。