Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is numeric? [duplicate]

Tags:

java

I have a gpa program, and it works with the equalsIgnoreCase() method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?

like image 606
user1944277 Avatar asked Jan 08 '13 01:01

user1944277


People also ask

How do I check if a string has repeated characters?

If we want to know whether a given string has repeated characters, the simplest way is to use the existing method of finding first occurrence from the end of the string, e.g. lastIndexOf in java. In Python, the equivalence would be rfind method of string type that will look for the last occurrence of the substring.

How do you check if a string index is a number in Python?

Return true if all characters in the string are digits and there is at least one character, false otherwise. For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode. isdecimal() / str. isdecimal() instead; not all Unicode digits are interpretable as decimal numbers.


1 Answers

Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric

One more is

public boolean isNumeric(String s) {       return s != null && s.matches("[-+]?\\d*\\.?\\d+");   }   

Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.

like image 160
Karthik T Avatar answered Sep 22 '22 01:09

Karthik T