简体   繁体   中英

How do I terminate a Java program if a certian condition isn't met?

Our project is to write a program that will validate credit card numbers. I am wanting to put a validation check at the beginning of the program so if the user enters a number that has less than 13 digits or more than 16 digits it displays an error message and then ends the program. I have read on here that the best (most graceful) way of doing it is to let the program run itself out. However, throughout the program I have other information displayed. So currently it will display the error message and then continue on with the program.

Any advice will be most helpful.

I think that your best chance would be to use some form of a conditional statement that checks the number they enter. Depending on what you want, a nested if or if else statement might be best.

You can calculate the number of digits using the following snippet:

int length = (int)(Math.log10(n)+1) //here n is your number

and further, you can continue to program like this:

if(length<13 || length>16) {
    //Print your error message
}

else {
    //Your program
}

As long as you are in the main() method of the program you can just call return to exit your program. In all other places you can exit the execution of your program using System.exit(1) with 1 replaced by the exit code you want to return. Normally you will return 0 to indicate success (correct credit card number) and a different number to indicate failures like an incorrect credit card number.

If the code is contained in a switch statement, a loop or an if statement you could always use the break; statement to exit you out of the code (loop, switch etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM