迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

在 Java 中使用 System.exit() 方法

作者:迹忆客 最近更新:2023/10/17 浏览次数:

本教程介绍了 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便