-2

I am just a beginner. Am trying to validate if an input is numeric and not a string. I can't seem to get the correct result. It's always false.

import javax.swing.JOptionPane;

public class CheckDigit 
{
    public static void main(String[] args)
    {
        String containsOnlyNumbers;
        containsOnlyNumbers = JOptionPane.showInputDialog("Please enter some numbers: ");
        // System.out.println(containsOnlyNumbers("12345"));
        // System.out.println(containsOnlyNumbers("12abc345"));
        if (false)
        {
            JOptionPane.showMessageDialog(null, "False!");   
        }
        else
        {
            JOptionPane.showMessageDialog(null, "True!");  
        }  
    }

    public static boolean containsOnlyNumbers(String str)
    {
        for (int i = 0; i < str.length(); i++)
        {
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }
        return true; 
    }
}

Please advise. TIA.

rlee
  • 11
  • 7
  • 1
    Do you need to do that yourself? If not try Apache Commons' `StringUtils` which has a method that does exactly what you want. – Thomas Aug 11 '15 at 08:21
  • 5
    possible duplicate of [How to check if a String is a numeric type in Java](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java) –  Aug 11 '15 at 08:21
  • 4
    What do you except to happen, if you use this statement `if (false)` – SomeJavaGuy Aug 11 '15 at 08:23

2 Answers2

1

If your want to use your solution you have to replace

if (false)

with

if (!containsOnlyNumbers(containsOnlyNumbers))

because you are not calling your method (same name for method and String).

ageh
  • 91
  • 10
0

You can also try like this,

  public static boolean numericCheck(String str)
  {

  try{
          double d=Double.parseDouble(str);

      }catch(NumberFormatException e)
       {
          return false;
       }

   return true;

}

if method return true then input is a number, if return false input is not numeric

Anptk
  • 1,125
  • 2
  • 17
  • 28