简体   繁体   中英

How to stop program from crashing?

I want the program to not crash when the user inputs anything other than a number. For example, if someone enters random letters, it should display a message saying, "input not valid, please enter a valid integer". Then prompting them if they would want to continue or not.

public static void main(String[] args) throws IOException {

    BufferedWriter out = new BufferedWriter(new FileWriter("outDataFile.txt"));

    Scanner input=new Scanner(System.in);
    int choice = 0;
    String repeat;

    //Loop repeats program until user quits
    do
    {
        //Loop repeats until a valid input is found
        do
        {
            //Asks for number and reads value
            System.out.print("\nEnter an integer and press <Enter> ");
            choice = input.nextInt();

            //Prints error if invalid number
            if(choice <= 0)
                System.out.println("Invalid Input.");

There are multiple ways to achieve that:

First is to catch the exception thrown by the Scanner and flag the loop to carry on when an exception is caught. This is not a good practise since the exception thrown by the Scanner , InputMismatchException , is an unchecked exception. Meaning the cause of this exception can be easily caught by an if/else statement.

In your case, you should try to receive the input as a String , then validate the input if it looks like a number:

Loop per character approach:

String string = scanner.nextLine();
for (int i = 0; i < string; i++) {
    char ch = string.charAt(i);
    if (!Character.isDigit(ch)) {
        System.out.println("Input is not a number");
        break; // stop the for-loop
    }
}
int input = Integer.parseInt(string);

RegEx approach:

String numericRegex = "[0-9]+";
String string = scanner.nextLine();

if (!string.matches(numericRegex)) {
    System.out.println("Input is not a number");
}
int input = Integer.parseInt(string);

These are popular approach to your problem, it is now up to you on how will you control your loops to repeat when an invalid input is encountered.

Use a simple try catch that will catch and a simple recursive method as such:

import java.util.InputMismatchException; import java.util.Scanner;

public class Test
{
    public static void main(String[] args)
    {
        System.out.println(getUserInput());
    }

    private static int getUserInput()
    {
        int choice = 0;

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a value");
        try
        {
            choice = input.nextInt();
        } catch (InputMismatchException exception)
        {
            System.out.println("Invalid input. Please enter a numeric value");
            getUserInput();
        }
        return choice;
    }
}

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