Reputation: 39
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");
}
}
}
Upvotes: 1
Views: 2225
Reputation: 44834
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
}
Upvotes: 2
Reputation: 2098
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);
}
}
Upvotes: -1
Reputation: 2594
You should check you string for numbers like this:
a=sc.nextLine();
if (a.matches(".*\\d+.*")) {
throw new InputMismatchException();
}
Upvotes: 0
Reputation: 74605
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.
Upvotes: 0