Which exception can i use to check if the input has the right number of "/" The input should be like DD/MM/YYYY

try{
                String str = text.getText();
                StringTokenizer st = new StringTokenizer(str);
                String DD = st.nextToken("/");
                String MM = st.nextToken("/");
                String YYYY = st.nextToken();
}
catch( ???){

}
有帮助吗?

解决方案

You will find it in the javadoc of nextToken. It says it will throw a NoSuchElementException when there is no more token.

That said you should better not use the try/catch but test it using the hasMoreTokens method.

其他提示

You can use Custom Exception for this but for that you need to declare method which validate your date (No of slashes).

Try Like this

   public class Demo
      {


  public static void main (String[] args) {

      try {
        new MyClass().metToValidate("01/12/2014");
          } catch (A e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
          }

      }

}
class A extends Exception{}


class MyClass{
      public void metToValidate(String dateText) throws A{


                if( dateText.charAt(2) == '/'&& dateText.charAt(5) == '/' )
                    System.out.println("DATE IS OK"); 

                else
                    throw new A();
      }
    }

The exception throws by nextToken is NoSuchElementException.

            String str = "12/21223";
            int counter = 0;
            for( int i=0; i<str.length(); i++ ) {
                if( str.charAt(i) == '/' ) {
                    counter++;
                } 
            }
            if(counter == 3){
                StringTokenizer st = new StringTokenizer(str);
                String DD = st.nextToken("/");
                String MM = st.nextToken("/");
                String YYYY = st.nextToken();
                System.out.println(str);
            }else{
                System.out.println("Exception");
            }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top