I have a string variable that is set equal to userInput.nextLine(), I want to check if this string contains anything other than numeric values.
if(string has non-numeric) {
break;
}
I have a string variable that is set equal to userInput.nextLine(), I want to check if this string contains anything other than numeric values.
if(string has non-numeric) {
break;
}
Try Catch may be another alternative way.
try{
Long.parseInt(string);
do what ever youy need to do with your number value.
}catch(NumberFormatException ex){
}
use string.matches(regex)
function. The regular expression would be \\d+
and check against whither the output is false
.
The \d
is known as Predefined Character Classes and an expression X+
: means that X
occurs one or more times, which is known as Quantifiers.
if you wish to allow sign(+ or -
) to be counted as part of the numeric value, you should use "[\\+\\-]?\\d+"
expression which will match against input string "+523"
or "-563"
. Check the Pattern class documentation for more details about this expression.
If you wish to allow "."
in the numeric value as in the case of decimal point, Then you should use regular expression: "[\\+\\-]?(\\d+|\\d*\\.\\d+)"
which will match against all type of numeric input like "1254"
, "-.256"
, "+58.235"
etc.
Choose Any one of the pattern which will satisfy your need and than match against your input string checking wither it results in false
: meaning that not a valid numeric input.
String pattern = "[\\+\\-]?(\\d+|\\d*\\.\\d+)" ; // or only \\d+
//or [\\+\\-]?\\d+
if(!string.matches(pattern)) // not a valid numeric input {
}
If you want to show off, use a String.matches() with a regular expression. Or you could iterate over it, char by char, using String.charAt().
I think this will do
String str1 = "123456";
System.out.println(str1.matches("[^0-9]+"));
Output will be false
and if you do
System.out.println(str1.matches("[0-9]+"));
Output will be true