1

I want to take input as a string in Java and limit the user to not enter integer by using try catch.

import java.util.*;

public class trycatch { 

    public static void main(String args[]) { 

        Scanner sc=new Scanner(System.in);
        String a; 

        System.out.println("\n\nEnter the name"); 

        try { 
            a=sc.nextLine(); 

            System.out.println("You name is "+a); 
        } 

        catch(InputMismatchException b) { 
            System.out.println("There is problem with your input"); 
        } 
    } 
}
2
  • 1
    Consider reading stackoverflow.com/help/how-to-ask. Commented Oct 18, 2018 at 5:13
  • 1
    From the scanner you never get input in integer format. It is always string and after thant you have to cast it to integer if you want to. i.e. '123' can be cast to 123 Commented Oct 18, 2018 at 5:16

4 Answers 4

2

Test to see if it is an int and if not a Exception is thrown

a=sc.nextLine(); 
Integer.valueOf(a); // throws NumberFormatException

// this is number so go to top of loop
continue;
} catch(NumberFormatException b) { 
        System.out.println("There is NO problem with your input");
        // we can use `a` out side the loop 
} 
Sign up to request clarification or add additional context in comments.

5 Comments

This is useful because it helps, without doing all the work for him, leaving a learning opportunity to be had. Kudos
Question is "I want to take input as a string in Java and limit the user to not enter integer by using try catch" but your code is giving error when it is not a number. which is totally opposite what OP wants. Please correct me if I'm wrong.
@DhaRmvEErsiNgh Yes, I see where you are coming from. Ideally this should wrapped in a while loop, but I did not think that was where the OP was having trouble. Of course printing of the error message is also optional, but I am sure it would be more useful to have than not.
@ScaryWombat, actually your code seems inverted... It should throw an exception if the integer parsing succeeds, meaning it’s not text as OP wants...
@TomazFernandes Yes, you are right, I have adjusted my code
0

Take a look at this:

Does java have a int.tryparse that doesn't throw an exception for bad data?

Use that technique to try to parse what the user entered as an int. If the conversion succeeds, it means they entered an int, and you should throw an exception because you said you don't want them to enter an int (which I understood to mean you don't want them to enter a sequence of numbers only)

I haven't given you the exact answer/written your code for you because you're clearly learning java and this is an academic exercise. Your university/school isn't interested in teaching/assessing my programming ability, they're interested in yours, so there isn't any value to you in me doing your work for you :)

If you get stuck implementing what I suggest, edit your question to include your improved code and we can help again

As a side note, I suggest you make your error messages better that "there was a problem" Nothing is more frustrating to a user than being told there was a problem but not what it was or how to fix it.

Comments

0

You should check you string for numbers like this:

a=sc.nextLine();
if (a.matches(".*\\d+.*")) {
     throw new InputMismatchException();
}

7 Comments

What if more digits are entered than an int can store? And what if mixed chars and number are entered (the question as it stands doesn't seem to prohibit == Strictly speaking the spec isn't followed)
Since the code is about a name, I think it’s pretty safe to assume that the OP wants to prevent the user to enter any number. So it should throw the exception in case the input is John123, or 1John34. Good point tough.
Once upon a time, a long time ago in university I won an award for an assignment. The app I turned in was the crappest looking, nastiest use of a java ui out of all the submissions. It won because it followed the spec to the letter, and demonstrated exactly what it was supposed to with no flair at all. It was a valuable lesson- when someone hands you a spec to code, code the spec not your assumption of what you think the spec might have asked for if it were a better spec. See my comment on the other answer about whether suggesting advanced concepts like regex is a sensible idea here
I agree, that probably would be more like an ideal goal, but given the level of programming knowledge demonstrated, I think the assignment is probably in stages - 1) create an app that asks the user for a name, check they didn't enter an integer.. 2) modify the app to ask for an age, check that it's an integer between 5 and 99. .. That kind of thing. Jumping straight to regular expressions, for a class full of people that can barely work out how to assign a variable, or the difference between "1234" and 1234.. is a bit of a leap that clamours "He didn't do the work himself".. Baby steps, IMHO
I totally agree with you... Unfortunately I haven’t had this academic experience in IT, so it’s kind of difficult for me to think of that scenario by myself. I’ll try to think more on these terms when answering this kind of question here in StackOverflow. Thanks!
|
-1

This problem can be solved best with using Regular expression but since your requirement is to use try catch so you can you use below approach

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String a = null;

    System.out.println("\n\nEnter the name");

    try {
        // try to get Integer if it is number print invalid input(because we
        // don't want number)
        sc.nextInt();
        System.out.println("There is problem with your input");
    }
    //getting exception means input was not an integer
    // if input was not an Integer then try to read that as string and print
    // the name
    catch (InputMismatchException b) {
        a = sc.next();
        System.out.println("You name is " + a);
    }
}

2 Comments

so what happens if the OP enters a number, then another number?
@ScaryWombat you can input only on line with above code and that should not be a number.. it will not ask for 2nd input so OP cannot enter second number after entering a number. Even if you provide 2 space separated number in that case two this will fail and will print "There is problem with your input". Request you to please run the code before down-voting .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.