Home > Back-end >  How to check if input is string with Try Catch?
How to check if input is string with Try Catch?

Time:05-02

I have the following code with a try .. catch operation that checks whether or not it is a String. However , no matter the input it will not throw an exception . What I want it to do is check whether or not the input is text for example "Nick" and if its not to them throw an exception and prompt the user to try again.

public static void main(String args[]) {
    int c = 1
    String temp, name="" ;
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter name");

    while (c == 1) {
        try {
            temp = myObj.nextLine();
            name = temp;
            c = 2;
        } catch (InputMismatchException e) {
            System.out.println("Name is not a string. Try again.");
        }
    }
}

CodePudding user response:

Return type of nextline() is String. It means whatever is entered by user, it will be treated as a String(even if user enters a number, it will still be taken as a String). So there is no need in Exception handling in this case.

CodePudding user response:

Any input will be a String. If what you want is to check if there are any numbers or special characters inside instead of letters then u can loop through the String and use the Character.isAlphabetic() that will return false if any character is not alphabetic.

CodePudding user response:

I think this approach would work for you:

public static void main(String args[]){
    String name = "";
    Scanner myObj = new Scanner(System.in); 

    final String correctExpectedName = "Nick";
    bool nameIsAccepted = false;
    while(name.IsEmpty()) {
        System.out.print("Enter name: ");
        string tempInput = myObj.nextLine();
        if (correctExpectedName.equals(tempInput)) {
            name = tempInput; // here you can also use name = correctExpectedName;
        } else {
            System.out.println("Name is not correct. Please try again ...");
        }
    }
}

Please don't use exceptions to control your application logic flow. Exceptions have different purpose.

  •  Tags:  
  • java
  • Related