Java 如果语句为假,有没有办法结束程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21962027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:40:37  来源:igfitidea点击:

Is there a way to end the program if statement is false?

javaif-statement

提问by MrBixbite

I am a just a beginner Java programmer and I was just wondering if there is a way to end the program if the user input is false. Here is an example:

我只是一个初级 Java 程序员,我只是想知道如果用户输入为假,是否有办法结束程序。下面是一个例子:

if (age > 13) {
    System.out.println("You are eligible for this site, you may proceed. ");
} else {
 // End program here if statement = false
}

(Please answer with the code if you don't mind.)

(如果您不介意,请用代码回答。)

采纳答案by ImGone98

if (age > 13) {
    System.out.println("You are eligible for this site, you may proceed. ");
}else{
    System.exit(0); 
}

This should end it!

这应该结束吧!

回答by paxdiablo

You can exit your program with System.exit().

您可以使用 退出程序System.exit()

See http://docs.oracle.com/javase/7/docs/api/java/lang/System.htmlfor more details.

有关更多详细信息,请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/System.html

回答by knightsb

if you on main just write return;

如果你在 main 上只写 return;

回答by Dexters

if this is in main() method

如果这是在 main() 方法中

just use return

只是使用 return

if this is in another function return something back to the main like a booleanthen return

如果这是在另一个函数中,则将某些内容返回到 main 中,例如booleanthenreturn

回答by JB Nizet

This will exit the JVM.

这将退出 JVM。

System.exit(-1); // or any other status

If this is the main method, you can also simply return from it (provided you haven't started a thread):

如果这是主方法,您也可以简单地从它返回(前提是您还没有启动线程):

return;

回答by ltalhouarne

You can end it this way:

你可以这样结束:

if (age > 13) {
    System.out.println("You are eligible for this site, you may proceed. ");
}else{
    System.exit(0); //code to end program
}