You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用return语句终止Java程序错误分支的执行

如何在不使用return的情况下终止Java程序(输入非法值时)

问题背景

现有一段面包店库存与购买的Java代码,原本在输入非法值(比如负数)时用return终止程序,但现在要去掉所有return语句,同时保证输入非法值时程序能立刻终止,不执行后续代码。

原代码如下:

import java.util.Scanner;
public class JavaClass {
public static void main(String args[]) {

Scanner scan=new Scanner(System.in);

System.out.println("Welcome to Baugette Store! ");

System.out.println("*****Bakery Inventory*****");
System.out.print("Enter amount of Baugette:");
int amount1=scan.nextInt();
if(amount1<0) {
    System.out.println("Error.");
    return;
}
System.out.print("Enter Price of Baugette:");
double price1=scan.nextDouble();
if(price1<0) {
    System.out.println("Error.");
    return;
}
System.out.println("**Customer Interface**");
System.out.println("Welcome to our baugette store. ");
System.out.println("We have "+price1+ " baugette(s) available.");
System.out.println("How Many Baugette(s) Do You Want to Buy?");
int amount2=scan.nextInt();
if(amount2<=0) {
    System.out.println("Error.");
return;
}
if(amount2>amount1) {
    System.out.println("Error.");
    return;
}
else {
System.out.println("You want to buy "+amount2+ " baugette(s).");
double totalcost,r;
totalcost=amount2*price1;
r=amount1-amount2;
System.out.println("Yours cost is "+(int)totalcost+" Turkish lira(s)");
System.out.println("Now, We have "+(int)r+" baugette(s) remaining.");
System.out.println("Thank you for shopping from Kolantro Baugette Shop today.");
System.out.println("Good bye :)");
}
}
}

可行实现方式

1. 用System.exit(int)直接终止进程

System.exit()会直接结束整个JVM进程,参数用非0值(比如1)标记异常退出,替换掉原来的return即可。

修改后的关键代码片段:

if(amount1<0) {
    System.out.println("Error.");
    System.exit(1); // 替换return,直接终止程序
}
// 其他错误判断同理替换
if(price1<0) {
    System.out.println("Error.");
    System.exit(1);
}
if(amount2<=0) {
    System.out.println("Error.");
    System.exit(1);
}
if(amount2>amount1) {
    System.out.println("Error.");
    System.exit(1);
}

2. 嵌套if结构控制执行流程

把所有正常业务逻辑放在校验通过的if分支里,非法输入时只会执行错误提示,不会进入后续代码,main方法执行完自然终止。

修改后的完整代码:

import java.util.Scanner;
public class JavaClass {
public static void main(String args[]) {

Scanner scan=new Scanner(System.in);

System.out.println("Welcome to Baugette Store! ");

System.out.println("*****Bakery Inventory*****");
System.out.print("Enter amount of Baugette:");
int amount1=scan.nextInt();
if(amount1>=0) { // 数量合法才继续
    System.out.print("Enter Price of Baugette:");
    double price1=scan.nextDouble();
    if(price1>=0) { // 价格合法才继续
        System.out.println("**Customer Interface**");
        System.out.println("Welcome to our baugette store. ");
        System.out.println("We have "+price1+ " baugette(s) available.");
        System.out.println("How Many Baugette(s) Do You Want to Buy?");
        int amount2=scan.nextInt();
        if(amount2>0) { // 购买数量合法才继续
            if(amount2<=amount1) { // 库存足够才执行购买逻辑
                System.out.println("You want to buy "+amount2+ " baugette(s).");
                double totalcost,r;
                totalcost=amount2*price1;
                r=amount1-amount2;
                System.out.println("Yours cost is "+(int)totalcost+" Turkish lira(s)");
                System.out.println("Now, We have "+(int)r+" baugette(s) remaining.");
                System.out.println("Thank you for shopping from Kolantro Baugette Shop today.");
                System.out.println("Good bye :)");
            } else {
                System.out.println("Error.");
            }
        } else {
            System.out.println("Error.");
        }
    } else {
        System.out.println("Error.");
    }
} else {
    System.out.println("Error.");
}
}
}

3. 布尔标志位控制流程

定义一个布尔变量标记校验状态,每次校验失败就把状态设为false,后续代码只有在状态为true时才执行。

修改后的完整代码:

import java.util.Scanner;
public class JavaClass {
public static void main(String args[]) {

Scanner scan=new Scanner(System.in);
boolean isValid = true; // 标记校验是否通过

System.out.println("Welcome to Baugette Store! ");

System.out.println("*****Bakery Inventory*****");
System.out.print("Enter amount of Baugette:");
int amount1=scan.nextInt();
if(amount1<0) {
    System.out.println("Error.");
    isValid = false;
}

if(isValid) { // 校验通过才执行价格输入
    System.out.print("Enter Price of Baugette:");
    double price1=scan.nextDouble();
    if(price1<0) {
        System.out.println("Error.");
        isValid = false;
    }

    if(isValid) { // 价格校验通过才执行购买流程
        System.out.println("**Customer Interface**");
        System.out.println("Welcome to our baugette store. ");
        System.out.println("We have "+price1+ " baugette(s) available.");
        System.out.println("How Many Baugette(s) Do You Want to Buy?");
        int amount2=scan.nextInt();
        if(amount2<=0) {
            System.out.println("Error.");
            isValid = false;
        }

        if(isValid && amount2>amount1) {
            System.out.println("Error.");
            isValid = false;
        }

        if(isValid) { // 所有校验通过才执行购买逻辑
            System.out.println("You want to buy "+amount2+ " baugette(s).");
            double totalcost,r;
            totalcost=amount2*price1;
            r=amount1-amount2;
            System.out.println("Yours cost is "+(int)totalcost+" Turkish lira(s)");
            System.out.println("Now, We have "+(int)r+" baugette(s) remaining.");
            System.out.println("Thank you for shopping from Kolantro Baugette Shop today.");
            System.out.println("Good bye :)");
        }
    }
}
}
}

内容的提问来源于stack exchange,提问作者pissgon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:01:01