-2

I'm trying to do error checking on a form. I wanted to see if a phone number is valid by if it has all numbers in it. Is there a way to see if a string only has nmbers in it?

Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • 1
    Just making sure, it's not a HTML form? Either way: of course there is. One way would be a pattern/regex. You should do your research. – keyser Jul 29 '14 at 22:13
  • 1
    Regular expressions would be one choice to allow strings like "(385)-141-3423" to be accepted. – Kayaman Jul 29 '14 at 22:14
  • depends can you add a sample accepted number format. – Rod_Algonquin Jul 29 '14 at 22:15
  • Assuming that you don't want to check for a pattern as well. Then you can check ASCII values of each digit/char in a loop. `if(string.charAt(i) < 48 || string.charAt(i) > 58){//Not number}` – gkrls Jul 29 '14 at 23:12

2 Answers2

2

You can use regex for this:

if(value.matches("[0-9]+")) {
    System.out.println("Only numbers!");
}
Vennik
  • 565
  • 3
  • 11
  • 1
    ...so you're saying that if I submit a numerical value, it will return "Only numbers!"?? Your `if` statement may be incorrect. – Mike Koch Jul 29 '14 at 22:17
0

Pattern for validating phone number with regex

"\\d{3}-\\d{7}"

for example:

 310-6666666

or

if you want just to read integer from your string

public class Agent{
 public static void main(String...args){
    String input = "1 23 35 5d 8 0 f";
    List<Integer> intList = new ArrayList<Integer>();

Arrays.asList(input.split(" ")).stream().forEach( i -> {
        try{
          intList.add(Integer.parseInt(i));
        }catch(Exception ex){

        }
});

intList.forEach( i -> System.out.print(" " + i));

}

ouput:

1 23 35 8 0
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58