java - Check if string taken with Scanner.next() contains number -


I wanted to take a string using the scanner .next () and see if there is a number in it or not. I used regex to check whether there is a number in the string but there is a number. The rajx works correctly if the string is coded hard, but not with the keyboard. I hope 5 will be detected as numbers, but it is not. Please tell me why. My code:

  import java.util.Scanner; Public class error {public static zero main (string [] args) {scanner inp = new scanner (System.in); Int num = 0; String input = ""; Boolean isStringNumber = true; System.out.println ("\ nPlease enter only one number ..."); Input = inp.nextLine (); IsStringNumber = input.contains ("[^ 0- 9] +"); If (isStringNumber == incorrect) {System.out.println ("\ nYou have entered a non-number" + input); }}}}  

A string as its argument > Uses. Instead, use mail

  isStringNumber = input.matches ("[0-9] +");  

Or simply

  isStringNumber = input.matches ("\\ d +");  

BTW: scanner has a nextInt method to accept the integer value


Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -