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"); 
        } 
    } 
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • 1
    Consider reading https://stackoverflow.com/help/how-to-ask. – Rarblack Oct 18 '18 at 05: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 – Rarblack Oct 18 '18 at 05:16

4 Answers4

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 
} 
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • This is useful because it helps, without doing all the work for him, leaving a learning opportunity to be had. Kudos – Caius Jard Oct 18 '18 at 05:30
  • 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. – DhaRmvEEr siNgh Oct 18 '18 at 07:20
  • @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. – Scary Wombat Oct 18 '18 at 10:59
  • @ScaryWombat, actually your code seems inverted... It should throw an exception if the integer parsing succeeds, meaning it’s not text as OP wants... – Tomaz Fernandes Oct 18 '18 at 11:24
  • 1
    @TomazFernandes Yes, you are right, I have adjusted my code – Scary Wombat Oct 18 '18 at 23:44
0

You should check you string for numbers like this:

a=sc.nextLine();
if (a.matches(".*\\d+.*")) {
     throw new InputMismatchException();
}
Tomaz Fernandes
  • 2,429
  • 2
  • 14
  • 18
  • 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) – Caius Jard Oct 18 '18 at 05:23
  • 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. – Tomaz Fernandes Oct 18 '18 at 05:34
  • 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 – Caius Jard Oct 18 '18 at 05:40
  • I get the feeling that the next step of this assignment (it feels like a "just started uni" one) will be to ask the age, and re use the int check code to verify the input is valid.. but we should of course still just code the spec as given :) – Caius Jard Oct 18 '18 at 05:42
  • What you say does make sense... Thing is we have different views on what his requisite is... I’m thinking he wants to filter out things like “john1234”. It’s not that clear on the question... I wouldn’t see any problem in introducing a simple regex also. But given your academic background, you’re most likely right. What you say looks like something a college teacher would assign :) – Tomaz Fernandes Oct 18 '18 at 11:20
  • 1
    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 – Caius Jard Oct 18 '18 at 14:31
  • 1
    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! – Tomaz Fernandes Oct 18 '18 at 15:08
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.

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
-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);
    }
}
DhaRmvEEr siNgh
  • 1,918
  • 2
  • 13
  • 17
  • so what happens if the OP enters a number, then another number? – Scary Wombat Oct 18 '18 at 06:51
  • @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 . – DhaRmvEEr siNgh Oct 18 '18 at 07:14