0

I want to create a class that will serve me as an exception. I will give you two examples of how I tried. I've been looking for it but I can't find an example of how to put this into practice, or it doesn't work for me.

This is my method where user choose flight by ID, I want to throw an exception if a program user enters a String.

Code:

@Override
public void choosePassenger(ArrayList<Passenger> passengerList) {
    System.out.println("Choose passenger by ID: ");
    try {
        int pickedPassenger = scanner.nextInt();
        for (Passenger tempUser : passengerList) {
            if (pickedPassenger == tempUser.getId()) {
                System.out.println("You picked passenger: " + tempUser.getFirstName() + ", "
                        + tempUser.getLastName() + ". Balance is: " + tempUser.getBalance());
                selectedPassenger = tempUser;
                break;
            }
        }
    } catch (InputMismatchException e) {
        System.out.println("Wrong input! Try again");
        scanner.nextLine();
    }
}

I tried on that way but after program show me message Wrong input! Try again it goes to another method not giving me chance to enter valid input

Also, how I can create exception here for just Strings?

System.out.print("Add name of passenger: ");
    passenger.setFirstName(scanner.nextLine());

This is part of code that enable program user to create new user, he is adding here name, I want to create exception so if program user add integer for name I want to show him an exception

EDIT:

If I delete scanner.nextLine(); program stops but first print me my own exception message then print me message from next method and then InputMissMatchException for that method on his own because I input string instead of integer

asu
  • 61
  • 5
  • Does this answer your question? [How can I write custom Exceptions?](https://stackoverflow.com/questions/1070590/how-can-i-write-custom-exceptions) – Yoshikage Kira Jun 01 '21 at 20:07
  • First you have to consider "Why do I need to stray away from the current available exceptions?" AND most importantly, "How can I avoid exceptions altogether?". No one wants to encounter an exception, **especially** a User of your application. – DevilsHnd - 退職した Jun 01 '21 at 20:23
  • Hi, I'm currently practicing, maybe in this case I don't need a special exception because the program itself is already doing it, but I want to learn how to implement it manually. – asu Jun 01 '21 at 20:33
  • It is bad idea to put any kind of limitations on names. For a while, Prince changed his name to an unpronounceable syllable. Then, there is Frank Zappa's daughter, Moon Unit (her first name). Then, there are a large number of Americans with first initials and middle names; for most of my life i refused to enter my middle name in any field except middle name fields. I have been told there are people with numerical names. – NomadMaker Jun 01 '21 at 21:47

1 Answers1

0

If you want the user to try again, you can keep them in an infinite loop that breaks after correct input.

Editing as per @DevilsHnd observation. You cannot use scanner.nextInt() in this manner as it will read without user being prompted for input and it results in being stuck in an infinite loop. You can then use nextLine() and validate the input is a number like this:

while(true) {
    try {
        int pickedPassenger = Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException e) {
        System.out.println("Wrong input! Try again");
    }
}

For restricting input to a non numeral value as you want for the name, you would have to check if the value entered is a number (there is no scanner method to restrict reading to non numeral values)

Most elegant way in my opinion is to use an external library that has this like Apache Commons:

while(true) {
    String firstName = scanner.nextLine();
    if (!NumberUtils.isCreatable(firstName )) {
        passenger.setFirstName(firstName );
        break;
    } else {
        System.out.println("Value cannot be a number!");
    }
}

However, if you cannot import external libraries, simplest way to do this is by using built in Java Integer.parseInt() function(although you might want to consider regex - see link below):

while(true) {
    String firstName = scanner.nextLine();
    try {
        Integer.parseInt(firstName);
        System.out.println("Value cannot be a number!");
    } catch (NumberFormatException e) {
        passenger.setFirstName();
        break;
    }
}

For more options on checking if a value is a number (like regex) check this: https://www.baeldung.com/java-check-string-number