Check string validity with pattern

hello,
I want to check the validity of strings given by the user. The only characters authorized are : 'a' to 'z', 'A' to 'Z', '0' to '9', '.', '-', '_', '*', '@' and ' ' (space)
i want to check this string with a pattern but it does not work.
Somebody can help me for the pattern because the API javadoc is poor and i have a limited web access in my agency.
Thanks
   String regex = "[a-zA-Z0-9.*-_@]";
   System.out.println(regex);
   boolean bol = Pattern.matches(regex, field);
   System.out.println(bol);
   ->> result always false for string field="Indy jones";

try this:
import java.sql.*;
import java.io.*;
import java.util.regex.*;
import java.util.*;
public class RegExTest2 {
public static void main (String args[]) {
Pattern pat = null;
Matcher m = null;
String patternToMatch = "^[a-zA-Z0-9\\.\\*\\-\\_@\\s]+$";
String line1 = "IndianaJones";
String line2 = "Indiana Jones";
String line3 = "Indiana - Jones";
String line4 = "Indiana&Jones";
String line5 = "Indiana & Jones";
String line6 = "  Indiana Jones  ";
String line7 = "Indiana Jones =";
pat = Pattern.compile(patternToMatch);
System.out.println("Pattern to match = " + patternToMatch);
boolean bol = Pattern.matches(patternToMatch, line1);  
System.out.println("line1 : expected true and got " + bol);
bol = Pattern.matches(patternToMatch, line2);  
System.out.println("line2 : expected true and got " + bol);
bol = Pattern.matches(patternToMatch, line3);  
System.out.println("line3 : expected true and got " + bol);
bol = Pattern.matches(patternToMatch, line4);  
System.out.println("line4 : expected false and got " + bol);
bol = Pattern.matches(patternToMatch, line5);  
System.out.println("line5 : expected false and got " + bol);
bol = Pattern.matches(patternToMatch, line6);  
System.out.println("line6 : expected true and got " + bol);
bol = Pattern.matches(patternToMatch, line7);  
System.out.println("line7 : expected false and got " + bol);
  } // end main
} //End Class RegExTest2

Similar Messages

  • Check data valid with Java Script

    Hi, every one,
    I made a jsp program and just to check if the data is valid before submit. My problem is even the data is invalid, it still go to next jsp page and display alert message at the same time. But I think if the data is invalid, we can't go to next jsp page. So, any one can tell me what's wrong with my program.
    Thanks in advance.
    The source code is as follows:
    <HTML><HEAD>
    <TITLE>TEST PROGRAM</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    function validate(){
         if(document.form1.yourname.value.length < 1){
              alert("please enter your full name");
              return false;
         if(document.form1.address.value.length < 3){
              alert("please enter your address.");
              return false;
         if(document.form1.phone.value.length < 3){
              alert("please enter your phone number");
              return false;
         return true;
    </SCRIPT>
    </HEAD>
    <BODY>
    <H1>FORM EXAMPLE</H1>
    Enter the following information. When you press the Display button,
    the data you entered will be validated, then sent by e-mail.
    <form name="form1" action="a2.jsp" enctype="text/plain" onSubmit="validate();">
    <p>
    <b>Name:</b><input type="text" length="20" name="yourname">
    <p>
    <b>Address:</b>
    <input type="text" length="30" name="address">
    <p>
    <b>Phone:</b><input type="text" length="15" name="phone">
    <p>
    <input type="SUBMIT" value="Submit">
    </FORM>
    </BODY>
    </HTML>

    Hi,
    I have another question. If i have a menu as follows and I just want to check the data valid on the current page. I mean, only value=1, 2,3 is valid, value=0 is invalid. How can I do?
    <td valign="middle" width="63%"> <font face="Arial, Helvetica, sans-serif" size="2">
    <select name="type">
    <option value="0">Please Select One of The Following Reasons</option>
    <option value="1">Exchange</option>
    <option value="2">Refund</option>
    <option value="3">Wrong Product</option>
    </select>
    </font></td>
    </tr>
    Thanks.
    peter

  • Using Validator with mx:ComboBox causes it to auto-close

    I've recently ported a 3.x flex app to Flex 4. I've run in to a bug that causes all mx:ComboBoxes to close the first time the user attempts to open the drop down list. Subsequent attempts to open the box work fine.
    Example:
    <mx:ComboBox id="typeId" dataProvider="{fMechanismTypes}"
                                 labelField="name" prompt="Select..."
                                 change="handleTypeChange( )"
                                 creationComplete="initTypeValidator();"
                                 focusOut="tabValidationCheck()"/>
    private function initTypeValidator():void {
                fTypeValidator.source = typeId;
                fTypeValidator.property = "selectedIndex";
                fTypeValidator.minValue = 0;
                fTypeValidator.lowerThanMinError = "This field is required.";
    If I don't initialize fTypeValidator, the combobox works correctly.
    Anyone experience this?

    It appears a Flex ComboBox and a String Validator with the properties of being required as true, and the property of text, forces the ComboBox to close when selecting an item via the keyboard.  This auto close only happens when making the initial selection from the initial empty string or 0 index.  After a valid selection has been made, the user is able to use the keyboard to select any other values, and the ComboBox display remains open.  I have attempted to write my own ComboBox class that extends the Flex ComboBox, which would do custom open and close functionality, however I have been unsuccessful.  My goal is to have this ComboBox remain open during Keyboard input.  If the StringValidator required property is set to false, the box does not auto close.
    Any help on this topic would be greatly appreciated.
    And here is a sample of my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"  layout="absolute" minWidth="955" minHeight="600" creationComplete="init();">
        <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                [Bindable]private var _comboBoxDataProvider:ArrayCollection;
                private function init():void {
                    _comboBoxDataProvider = new ArrayCollection();
                    _comboBoxDataProvider.addItemAt('', 0);
                    for(var i:int = 0; i < 6; ++i) {
                        var obj:Object = {};
                        obj.labelField = String(i);
                        _comboBoxDataProvider.addItem(obj);
                    comboBoxValidator.validate();
            ]]>
        </mx:Script>
        <mx:StringValidator id="comboBoxValidator"
            required="true"
            source="{comboBox}" requiredFieldError="Empty Field Error"
            property="text"
            />
        <mx:ComboBox  id="comboBox" width="150"
        dataProvider="{_comboBoxDataProvider}"
        labelField="labelField"
        selectedIndex="0"  />
    </mx:Application>

  • I Have iPad4 and using with Aricel Prepaid 3G SIM, How to check my VAlidity period and balance amount through iPad?. pls help me

    I Have iPad4 and using with Aricel Prepaid 3G SIM, How to check my VAlidity period and balance amount through iPad?. pls help me, M.Kumar, Chennai,
    <Email Edited By Host>

    There are 2 concepts attached to a bank balance. The balance as per your books of accounts and another is the balance maintained with the bank. I believe i need not explain these 2 concepts. These 2 balances can be obtained from Oracle system provided some of prerequsities are met with.
    Balance as per your books - This is nothing but the GL balance available. In order to obtain balances for each bank accounts, it is advised that each bank account should have a separate account code combination. This is achieved generally by having a separate natural account for each bank. The code combination is attached to the cahs account for each bank. By maintaining separate account code combination, the balance in each code combination can be obtained from GL (provided transactions are accounted and posted in GL). These balances represent the balance for each bank according to your books of accounts. You can create an FSG for this purpose and provide the same to the customer, so that they can run the same whenevr they want.
    Balance as per bank - This balance is maintained by oracle in 2 ways - either the bank balance can be manually entered for each bank account for each date (quite cumbersome). Else, while loading the bank statement, the bank balances are also loaded. There are various types of bank balances stored - value dated balance, available balance, float balance etc. Depending on the balances provided by bank along with the bank statement, the bank balance can be recorded in oracle system. After the bank statement is uploaded and balances stored, standard cash management reports are available to query for the bank account balances. In order to view daily movement, the bank statement should be loaded on daily basis.
    Hope this helps.
    Vinit

  • XML validation with JDOM / JAXP

    Hello,
    I am trying to validate xml file against schema file. I decided to use JDOM and JAXP.
    First question: is it a good choice?
    I did a first attempt but not sure I have understood all what I am doing :(
    First I have create a parser usinf org.jdom.*
    SAXBuilder parser = new SAXBuilderThen I built my document:
    Document doc = parser.build(myFile)These 2 steps are ok. But it does not do validation.
    I saw in the JDOM documentation that I can set a validation flag to true. I did it. First problem, I got the following error from JDOMException: Document is invalid: no grammar found.
    Is there a way to specify to the parser where to find the xsd file?
    As I did not find answer to this question by myself, I tried implementing the Schema class from JAXP:
    SAXBuilder parser = new SAXBuilder;
    Document doc = parser.build(myFile);
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
    ValidatorHandler vh = schema.newValidatorHandler();
    SAXOutputter so = new SAXOutputter(vh);
    so.output(doc);It does the validation against the schema file specified but I am not really sure about what I am doing here. The last 2 commands are not clear to me :(
    Then in my schema file, I have elements that have default value. I expected the following behavior: if the element is not in the xml file then the default will be used by the parser (and added in the tree). But it seems, it's not the case.
    Any help/explanation will be really appreciated.

    I am trying to validate xml file against schema file. I decided to use JDOM and JAXP.
    First question: is it a good choice?
    If only schema validation is required use the validation API in JDK 5.0.
    http://www-128.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html
    http://java.sun.com/developer/technicalArticles/xml/validationxpath/
    For validation with JDOM, the following validation application explains the procedure:import org.jdom.input.SAXBuilder;
    import org.xml.sax.SAXException;import org.jdom.*;
    import java.io.*;
    public class JDOMValidator{
    public void validateSchema(String SchemaUrl, String XmlDocumentUrl){
               try{
    SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser",true);<br/>saxBuilder.setValidation(true);
    saxBuilder.setFeature("http://apache.org/xml/features/validation/schema",true);
    saxBuilder.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
    saxBuilder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",SchemaUrl);
    Validator handler=new Validator();
    saxBuilder.setErrorHandler(handler);
    saxBuilder.build(XmlDocumentUrl);
    if(handler.validationError==true)
    System.out.println("XML Document has Error:"+handler.validationError+""+
    handler.saxParseException.getMessage());      
    else           
          System.out.println("XML Document is valid");
              }catch(JDOMException jde){
                }catch(IOException ioe){
    private class Validator extends DefaultHandler{     
         public boolean  validationError = false; 
         public SAXParseException saxParseException=null;    
      public void error(SAXParseException exception) throws SAXException{        
         validationError =true;
         saxParseException=exception; 
      public void fatalError(SAXParseException exception) throws SAXException  {
    validationError = true;     
    saxParseException=exception;
      public void warning(SAXParseException exception) throws SAXException       {
    public static void main(String[] argv)   {
       String SchemaUrl=argv[0];StringXmlDocumentUrl=argv[1];
       JDOMValidator validator=new JDOMValidator();
       validator.validateSchema(SchemaUrl,XmlDocumentUrl);
    }

  • Check string input

    I tried to use pattern class to check user's input, here is the code
    public boolean InputCheck()
    String REGEX,REGEX_S;
    Pattern pattern;
    Matcher matcher;
    REGEX_S = "\n";
    Pattern p = Pattern.compile(REGEX_S);
    String[] items = p.split(data); //data is a string
    //first try to use split() to split string data to lines
    for(int i=0;i<items.length;i++)
    //then for each line of data ,check if it's ok for the format
    REGEX="^(-?\\d*)\\s(-?\\d*)$";
    pattern = Pattern.compile(REGEX);
    matcher = pattern.matcher(items);
    if (matcher.find()==false){
    return false;
    //if one line not, reture false
    can any one can tell me what's wrong with this code, cos the compiler keeps say ing there is a missing return statement,thanks

    This is because the return statement IS missing =P
    public boolean InputCheck() {
        String REGEX, REGEX_S;
        Pattern pattern;
        Matcher matcher;
        REGEX_S = "\n";
        Pattern p = Pattern.compile(REGEX_S);
        String[] items = p.split(data); //data is a string
        //first try to use split() to split string data to lines
        for(int i=0;i<items.length;i++)
        //then for each line of data ,check if it's ok for the format
            REGEX="^(-?\\d*)\\s(-?\\d*)$";
            pattern = Pattern.compile(REGEX);
            matcher = pattern.matcher(items);
            if (matcher.find()==false){
            return false;
            //if one line not, reture false
        return true; // <----- you've missed this!
    }

  • Check URL Validity

    Hello, I'm trying to figure out how to check the validity of a URL. I have wrote something, but it's not exactly what I want. Here is what I have:
         public boolean URLCheck(String checkme) {
              if((checkme.contains("http://") || checkme.contains("https://") ||
                        checkme.contains("ftp://")) && (checkme.contains(".edu") ||
                        checkme.contains(".com") || checkme.contains(".net") ||
                        checkme.contains(".org"))) {
                   return true;
              else{
                   output.setText("Bad URL.");
                   return false;
         }This is obviously very flawed, it only checks the protocol and the end of the server address (com,org,net,etc...).
    I would like to write a piece of code that could check if the URL is in this format, but I'm not sure where to begin.
    < url > ::= < protocol >://< server_address >/< local_address >
    < protocol > ::= http | https | ftp
    < server_address > ::= < host >.< domain > | < host>.< domain >:< port >
    < host > ::= < alphanumeric_character_string >
    < domain > ::= < alphanumeric_character_string > |
                   < alphanumeric_character_string >.< domain >
    < port > ::= < numerical_string >
    < local_address > ::= ~< login_name >/< location > | < location >
    < location > ::= < null_string > | < file_name > |
                     < path >/ | < path >/< file_name >
    < path > ::= < directory_name > | < directory_name >/< path >I'm not asking to have the code written for me, but I was wondering if someone could tell me how I could go about doing something like this.
    Thank you in advance!

    Thank you, here is what I tried:
         public void grabURLContents(String contents) throws Exception {
              try {
                   URL inputFile = new URL(contents);
                   BufferedReader in = new BufferedReader(
                                  new InputStreamReader(
                                  inputFile.openStream()));
                   String inputLine, storage = "";
                   while ((inputLine = in.readLine()) != null)
                       storage += inputLine +"\n";
                   output.setText(storage);
                   in.close();
              catch(Exception e) { output.setText("BAD URL: \n" + e); }
         }The only problem with this is: when I enter a url that obviously doesn't exist such as http://awdawfagasegr.com it still prints the html contents of my ISP's "Page not Found" page. Is there any way to prevent this?
    Thank you for your help by the way. Sorry if I seem very ignorant, I am not familiar with Java's URL class.

  • Help with comparing string array with parameters

    I've posted my code in full so hopefully everyone can see exactly what I have been doing.
    Note - my code uses the observer/observable model. The method I am having the problem with the if statement is in the class HSBC.
    Basically when the pin count reaches 4 (in the atm class) it sends the userid & pincode) over to the checkPinAndUserId(String pinCode, String userCode) method. Here the if statement should check the userid to see if the string parameter matches a string in the array. If it does it should check in the same position in the pin array to check the pin no is correct and then return true.
    * @(#)BankAssignment.java 1.0 03/04/06
    * This apllication l
    package myprojects.bankassignment;
    import java.awt.*; // import the component library
    import java.awt.event.*; // import the evnet library
    import javax.swing.*;
    import java.util.*;
    class Correct1v16 extends Frame // make a new application
         public Correct1v16() // this is the constructor method
              HSBC HSBCobj = new HSBC();
         public static void main(String args[]) // this invokes the constructor of the class and creates a runable object 'mainframe'
              Correct1v16 mainFrame = new Correct1v16(); // the constructor call of the class which creates an object of that class
    class HSBC implements Observer,  ActionListener
              Frame f5;
              JLabel refill, launch;
              TextField tRefill, tLaunch;
              JButton refillbut, launchbut;
              int count;
              String [] userId=new String [10];
              String [] pin=new String [10];
              public boolean authenticate = false;
              int i;
                   public HSBC()
                   drawFrame();
                   Atm Atmobj = new Atm(this);
                   System.out.println("Starting HSBC constructor");     
              public void drawFrame()
                   System.out.println("Start HSBC drawframe method...");
                   f5=new Frame("HSBC");
                   f5.setLayout(new FlowLayout());
                   f5.setSize(200, 200);
                   f5.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)     
                             f5.dispose();
                             System.exit(0);     
                   refill=new JLabel("Refill ATM");
                   launch=new JLabel("Launch new ATM");
                   tRefill=new TextField(20);
                   tLaunch=new TextField(10);
                   refillbut=new JButton("Refill ATM");
                   refillbut.addActionListener(this);
                   launchbut=new JButton("Launch new ATM");
                   launchbut.addActionListener(this);
                   f5.add(refill);
                   f5.add(tRefill);
                   f5.add(refillbut);
                   f5.add(launch);
                   f5.add(tLaunch);
                   f5.add(launchbut);
                   f5.setVisible(true);
    //*********** POPULATE THE ARRAYS     */
                   pin[0]="1234";
                   pin[1]="2345";
                   pin[2]="3456";
                   pin[3]="4567";
                   pin[4]="5678";
                   pin[5]="6789";
                   pin[6]="7890";
                   pin[7]="8901";
                   pin[8]="9012";
                   pin[9]="0123";
                   userId[0]="0";
                   userId[1]="1";
                   userId[2]="2";
                   userId[3]="3";
                   userId[4]="4";
                   userId[5]="5";
                   userId[6]="6";
                   userId[7]="7";
                   userId[8]="8";
                   userId[9]="9";
              }// end drawframe method
              //     public Atm atmLink = (Atm)o;
                   public void update(Observable gm1, Object o)
                        Atm atmLink = (Atm)o;
                        tRefill.setText("Refill ATM ?");
                        atmLink.refill();
                   }//end update method
                   public void actionPerformed(ActionEvent ae)
                        if(ae.getSource() == refillbut)
    //                         Atm Atmobj.refill();
                        //     tRefill.setText("text area");     
                        //     atmLink.refill();
    //                         Atmobj.refill();
    //                         setChanged();
    //                         notifyObservers();
                        if(ae.getSource() == launchbut)
                             tLaunch.setText("new ATM opened");
                             Atm Atmobj1 = new Atm(this);
    //******** THIS METHOD RECEIVES THE PARAMETERS FROM THE ATM METHOD (LINE 580) (PINCODE AND USERCODE) BUT
    //******** IT ONLY THE ARRAY CALLED USERID (WHICH HOLDS THE USER CODE MATCHES ONE OF THE USERID'S)
    //******** I DO WANT IT TO DO THIS BUT I ALSO WANT IT TO MOVE ON AND CHECK THE PINCODE WITH THE PIN ARRAY)
    //******** IF THEY ARE BOTH TRUE I WANT IT TO RETURN TRUE - ELSE FALSE.          */               
                   public boolean checkPinAndUserId(String userCode, String pinCode)
                        boolean found = false;
                        System.out.println("in checkpin method");
                        System.out.println("userCode = "+ userCode);
                        System.out.println("pinCode = " + pinCode);
                        for (int i = 0; i < userId.length; i++)
                        System.out.println("in the userid array" + userId);
                             if (userCode.equals(userId[i]))
                                  System.out.println("checking user code array");
                                  if (pinCode.equals(pin[i]))
                                       System.out.println("checking the pin array" + pinCode);
                                       System.out.println("pin[i] = "+pin[i]);
                                  found = true;
                        return found;
         }// end HSBC class
    class Atm extends Observable implements ActionListener
              Frame f1;
              TextField t3, t5;
              JTextArea display = new JTextArea("Welcome to HSBC Bank. \n Please enter your User Identification number \n", 5, 40);
              JPanel p1, p2, p3,p4;
              private JButton but1, but2, but3, but4,but5,but6,but7,but8,but9,but0,enter,
              cancel,fivepounds,tenpounds,twentypounds,fiftypounds,clearbut, refillbut;
              int state = 1;                                        
              public String pinCode ="";
              public      String userCode ="";
              int userCodeCount = 0;
              int PINCount = 0;
              String withdrawAmount = "";
              int atmBalance =200;
              private HSBC HSBCobj;     
              //ATM constructor that receives the HSBCobj g1 reference to where the HSBC class
              // in in the program
              // Calls the drawATMFrame method
              // add the observer to the HSBCobj reference so that the ATM can tell HSBC that
              // something has changed
              public Atm(HSBC g1)
                   HSBCobj = g1;
                   drawATMFrame();
                   System.out.println("Starting Atm constructor");
                   addObserver(HSBCobj);     
              // this is the method that draws the ATM interface
              // also apply the Border Layout to the frame
              public void drawATMFrame()
                   f1=new Frame("ATM");
                   f1.setLayout(new BorderLayout());
                   f1.setSize(350, 250);
                   f1.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)     
                             f1.dispose();
                             System.exit(0);     
                   // declare & instantiate all the buttons that will be used on the ATM
                   but1 =new JButton("1");
                   but1.addActionListener(this);
                   but2 =new JButton("2");
                   but2.addActionListener(this);
                   but3 =new JButton("3");
                   but3.addActionListener(this);
                   but4 =new JButton("4");
                   but4.addActionListener(this);
                   but5 =new JButton("5");
                   but5.addActionListener(this);
                   but6 =new JButton("6");
                   but6.addActionListener(this);
                   but7 =new JButton("7");
                   but7.addActionListener(this);
                   but8 =new JButton("8");
                   but8.addActionListener(this);
                   but9 =new JButton("9");
                   but9.addActionListener(this);
                   but0 =new JButton("0");
                   but0.addActionListener(this);
                   enter=new JButton("Enter");
                   enter.addActionListener(this);
                   cancel=new JButton("Cancel/ \n Restart");
                   cancel.addActionListener(this);
                   fivepounds =new JButton("?5");
                   fivepounds.addActionListener(this);
                   tenpounds = new JButton("?10");
                   tenpounds.addActionListener(this);
                   twentypounds = new JButton("?20");
                   twentypounds.addActionListener(this);
                   fiftypounds = new JButton("?50");
                   fiftypounds.addActionListener(this);
                   clearbut = new JButton("Clear");
                   clearbut.addActionListener(this);
                   refillbut = new JButton("Refill");
                   refillbut.addActionListener(this);
                   //declare & instantiate a textfield               
                   t3=new TextField(5);
                   // instantiate 4 JPanels     
                   p1=new JPanel();
                   p2=new JPanel();
                   p3=new JPanel();
                   p4=new JPanel();
                   // add some buttons to p1
                   p1.add(but1);
                   p1.add(but2);
                   p1.add(but3);
                   p1.add(but4);
                   p1.add(but5);
                   p1.add(but6);
                   p1.add(but7);
                   p1.add(but8);
                   p1.add(but9);               
                   p1.add(but0);
                   //add the text area field to p2
                   p2.add(display);
                   // apply the grid layout to p3
                   GridLayout layout3 = new GridLayout(4,1,5,5);
                   p3.setLayout(layout3);
                   p3.add(fivepounds);
                   p3.add(tenpounds);
                   p3.add(twentypounds);
                   p3.add(fiftypounds);
                   // apply grid layout to p4
                   GridLayout layout4 = new GridLayout(4,1,5, 5);
                   p4.setLayout(layout4);
                   p4.add(clearbut);
                   p4.add(enter);
                   p4.add(cancel);
                   p4.add(refillbut);
                   //add the panels to the different parts of the screen
                   f1.add("North", display);
                   f1.add("Center", p1);
                   f1.add("East", p4);
                   f1.add("West", p3);
                   f1.setVisible(true);
              }// end drawATMframe method
         public void actionPerformed(ActionEvent ae)
                   if(state == 1)
                             getUserIdNo(ae);
              else     if(state == 2)
                             doPINInput(ae);
                        else
                             withdrawCash(ae);     
         }// end action performed method               
    //******** STATE 1 events*/
    //******** USER ID INPUT*/
              public void getUserIdNo (ActionEvent ae)
                   if (ae.getSource() == but1)
                        display.append("*");
                        userCode = userCode + "1";
                        userCodeCount++;
                   if (ae.getSource() == but2)
                        display.append("*");
                        userCode = userCode + "2";
                        userCodeCount++;
                   if (ae.getSource() == but3)
                        display.append("*");
                        userCode = userCode + "3";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but4)
                        display.append("*");
                        userCode = userCode = "4";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but5)
                        display.append("*");
                        userCode = userCode + "5";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but6)
                        display.append("*");
                        userCode = userCode + "6";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but7)
                        display.append("*");
                        userCode = userCode + "7";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but8)
                        display.append("*");
                        userCode = userCode + "8";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but9)
                        display.append("*");
                        userCode = userCode + "9";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but0)
                        display.append("*");
                        userCode = userCode + "0";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == cancel)
                        display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                        userCode = "";
                        state = 2;
                   if (ae.getSource() == clearbut)
                        display.setText("Please enter your user ID number again\n");
                        userCode = "";
                        userCodeCount = 0;
                   if (ae.getSource() == refillbut)
                        refill();
                   if (ae.getSource() == enter)
                        display.setText("Please enter your PIN \n");
                        state = 2;
                        System.out.println(" User id enter button = " + userCode);
                   if (userCodeCount == 1)
                        display.setText("Please enter your PIN \n");
                        //userCode = "";
                        userCodeCount = 0;
                        state = 2;          
    //******** STATE 2               */
    //******** PIN INPUT*/
                   public void doPINInput(ActionEvent ae)
                        if (ae.getSource() == but1)
                             {      pinCode = pinCode.concat("1");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but2)
                             {      pinCode = pinCode.concat("2");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but3)
                             {      pinCode = pinCode.concat("3");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but4)
                             {      pinCode = pinCode.concat("4");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but5)
                             {      pinCode = pinCode.concat("5");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but6)
                             {      pinCode = pinCode.concat("6");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but7)
                             {      pinCode = pinCode.concat("7");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but8)
                             {      pinCode = pinCode.concat("8");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but9)
                             {      pinCode = pinCode.concat("9");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but0)
                             {      pinCode = pinCode.concat("0");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == clearbut)
                                  display.setText("Please enter your PIN number again \n");
                                  pinCode = "";     
                                  PINCount = 0;
                        if (ae.getSource() == cancel)
                                  display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                             state = 1;
                                  pinCode ="";
                                  PINCount = 0;                         
                        if (ae.getSource() == refillbut)
                                  refill();
    /// ************************ THIS BUTTON SENDS THE PIN & USER CODE OVER TO THE MAIN BANK*/
    /// ************************ (LINE 152)               */
                        if (ae.getSource() == enter)
    //                         if(HSBCobj.checkPinAndUserId(pinCode, userCode))
    //                              display.setText("How much would you like to withdraw \n");
    //                    else
    //                         display.setText("Your UserId and Pin code do not match");
                        if(PINCount ==4)
                        if(HSBCobj.checkPinAndUserId(userCode,pinCode))
                                  display.setText("Enter the amount you \n want to withdraw \n ?");
                                  PINCount=0;
                        else
                        display.setText("Your User Identification Number \n and PIN number do not match! \n please try again\n");     
    //*********** STATE 3 events*/
    //*********** withdrawCash*/
         public void withdrawCash(ActionEvent ae)
    //               if (ae.getSource() == but1)
    //                    display.append("1");
    ///                    withdrawAmount = withdrawAmount+1;
         //               pinCode = pinCode.concat("2");
         //               System.out.println("Withdrawal Amount = "+withdrawAmount);
                   if(ae.getSource( ) == but1)
                        withdrawAmount = withdrawAmount + "1";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but2)
                        withdrawAmount = withdrawAmount + "2";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but3)
                        withdrawAmount = withdrawAmount + "3";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but4)
                        withdrawAmount = withdrawAmount + "4";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but5)
                        withdrawAmount = withdrawAmount + "5";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but6)
                        withdrawAmount = withdrawAmount + "6";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but7)
                        withdrawAmount = withdrawAmount + "7";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but8)
                        withdrawAmount = withdrawAmount + "8";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but9)
                        withdrawAmount = withdrawAmount + "9";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but0)
                        withdrawAmount = withdrawAmount + "0";
                        display.setText(withdrawAmount);
                   if (ae.getSource() == fivepounds)
                        withdrawAmount = withdrawAmount + "5";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == tenpounds)
                        withdrawAmount = withdrawAmount + "10";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == twentypounds)
                        withdrawAmount = withdrawAmount + "20";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == fiftypounds)
                        withdrawAmount = withdrawAmount + "50";
                        display.setText(withdrawAmount);
                        atmBalance();
         //          if (ae.getSource() == tenpounds)
         //               display.append("10");
         //               withdrawAmount = 10;
         //               pinCode = pinCode.concat("2");
         //               System.out.println("10 pound button pressed");
         //               atmBalance();
                   if (ae.getSource() == enter)
                        atmBalance();
                   if (ae.getSource() == refillbut)
                        System.out.println("refill but pressed");
                        refill();     
                   if (ae.getSource() == clearbut)
                        System.out.println("clear but pressed");
                        display.setText("Enter the amount you want to withdraw \n ?");
                        withdrawAmount="";
                   if (ae.getSource() == cancel)
                        display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                        withdrawAmount="";
                   pinCode ="";
                        PINCount = 0;
                        userCode = "";
                        userCodeCount = 0;
                        state = 1;
         }// end withdraw cash input method
         // checks balace of atm and withdraws cash. Also notifies onserver if atm balance is low     
              public void atmBalance()
                   String s = withdrawAmount;
                   int n = Integer.parseInt(s);
                   if ( atmBalance >= n)
                        atmBalance = atmBalance - n;
                        System.out.println("atm balance = "+ atmBalance);
                        display.setText("Thankyou for using HSBC. \nYou have withdrawn ?"+n);
                        if     (atmBalance<40)
                             System.out.println("atm balance is less than 40 - notify HSBC" );
                             setChanged();
                             notifyObservers(this);
                             /// note the refil should send a message to the controller
                             // advising a refil is needed. The Bank will send an engineer
                             // out who will fill the atm up
              }// end atmBalance method
              /// note the refil should send a message to the controller
              /// then th coontroller will send a message to this method to fill machine
              /// (this is simulating a clerk filling atm)
                   public void refill()
                        System.out.println("in refill method" );
                        atmBalance = 200;
                        System.out.println("Atm has been refilled. Atm balance = " + atmBalance);
                   //     setChanged();
                   //     notifyObservers(this);
                   }// end refill method
    // NOTE SURE ABOUT THIS - DO I USE THE UPDATE METHOD TO NOTIFY HSBC THAT ATM REQUIRES FILLING
    // THIS IS THE WRONG PART OF THE PROGRAM (SHOULD BE IN HSBC) - IGNORE
                   public void update(Observable gm1, Object gameObj)
                        display.setText("Congratulations");               
                   }//end update method
         }// end Atm method
    }// end Assignment2 clas
    [\code]

    I wasn't trying to annoy anyone at all.
    I'm new to java and have been told that using the observer/observable model is not considered basic java. So that is the only reason I posted it in this section. At the same time i feel that the bit I'm struggling with is actually basic - hence posting it in the basic section. I'm not sure if people of all abilities check all forums or just the ones they feel at at their standard.
    So appologies if you've taken offence.

  • How to test if String starts with a Range of numbers

    Hello,
    I'm reading in a line from a text file and I want to see if that line starts with numbers.
    I know there is
    String temp = file.readline();
    if (String temp.startsWith(?1-9?); // want to check if string starts with 1 thru 9
    Thanks!

    Try the following:
    String temp = file.readline();
    if (temp.equals("1") || temp.equals("2")....... || temp.equals("9") {
    System.out.println("String is beetween 1 - 9");
    else{
    System.out.println("String is not beetween 1 - 9");
    Replace the "....." by the other values... I know it's quite long, but it should work... must be an easier way though...
    Pierre

  • XML validation: how to check ALL validation problem for XHTML

    I have a lot of documents in HTML format (not very good) that I would like to convert in XML (XHTML). I know it is not so easy and I would use this strategy in a Java program:
    1. Try to check the well-formness and validation with a XML parser (SAX or Xerces)
    2. If not valid: try to individuate ALL the problems the file has (*and not only the first one that halts the processing process*)
    3. Try to transform the HTML to a validable XHTML with some approach: regular expression or other methods
    So the questions I do to you are the following:
    1. What XML parser do you think is the best for this purposes? SAX or Xerces?
    2. How can I understand what are all the validation problems in the file and not only the first one (If I remember well XML parsers halt the parsing process at the first error...)?
    3. How can I transform the HTML to a valid XHTML? I have only to use RegEx or is there other tools to do this for XHTML and HTML problem?
    Thanks
    r
    Edited by: robertobat on Feb 21, 2009 7:09 PM

    >
    1. Neither of them. (Disregarding the fact that SAX and Xerces aren't in the same category and don't cover all the possibilities.I would say SAX default implementation in JRE and SAX parser in Xerces.
    2. I think you have "valid" and "well-formed" confused. And HTML isn't a dialect of XML so the idea of trying to use an XML parser to handle HTML isn't a good idea.I know very well what is the difference between valid and well-formed but I've used "validation" to represent all the conversion problem. But you are right. I'm convincing myself that using a XML parser as the first step is not a good idea.
    3. Well, this is the real question, isn't it? Those other two were just a waste. Don't screw about with regex, for one thing it doesn't work well for hierarchical structures and for another you won't finish in a finite time. Just use an HTML parser which can produce a DOM, like TagSoup for example. Or run them through HTMLTidy. You could also submit them to one of the internet sites which will validate XHTML for you.I've seen Tidy and its capability to convert an HTML to a XHTML and I think it is better then TagSoup because I have to implement this mechanism in a production environment and I want to use only open source projects that have a very long story and that are strong. But I'll see TagSoup as you say.
    I cannot use an Internet service to convert millions of private documents.

  • Schema Validation with Java and Document object

    Hi, I am working on a project that will validate an xml Document object from a child class. I seem to have completed XSD validation with new DOMSource(doc) and using schema factory, which doesn't support DTD validation. And now I am attempting to validate the DTD. It seems like all the examples I've seen are trying to parse files, and I am struggling with finding a way to validate it directly against the document object.
    The child class creates the xml document which is passed back to the parent class, and I need to do the validation in the parent class, so I need away to validate against the document object. This will be an assertion in Fitnesse if anyone is familar with it.
    private void doSchemaValidationCommand(int rowCount, Document doc, String xpathExpression)
             String validationPath = getText(rowCount,1);
             String extensionSeparator = ".";
             Boolean error = false;
             String ext = null;
             try
             int dot = validationPath.lastIndexOf(extensionSeparator);
            ext = validationPath.substring(dot + 1);
             catch(Exception e)
                  this.wrong(rowCount, 1, e.getMessage());
             if (ext.equalsIgnoreCase("xsd"))
             try {
             SchemaFactory factory =
                SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            File schemaLocation = new File(validationPath);
            Schema schema = factory.newSchema(schemaLocation);
            Validator validator = schema.newValidator();
            try {
                validator.validate(new DOMSource(doc));
            catch (SAXException ex) {
                this.wrong(rowCount, 1, ex.getMessage());
                error = true;
            catch (IOException ex)  {
                 this.wrong(rowCount, 1, ex.getMessage());
                 error = true;
           catch (SAXException ex) {
               this.wrong(rowCount, 1, ex.getMessage());
               error = true;
           catch (Exception ex){
                this.wrong(rowCount, 1, ex.getMessage());
                error = true;
             else if (ext.equalsIgnoreCase("dtd"))
                  try {
             }

    I tried this but it doesn't give me any validation of whether or not it was completed successfully, it just adds a tag for the dtd to the xml and doesn't seem to do anything further with it, am I missing any steps?
    else if (ext.equalsIgnoreCase("dtd"))
                  try {
                       DOMSource source = new DOMSource(doc);
                       StreamResult result = new StreamResult(System.out);
                       TransformerFactory tf = TransformerFactory.newInstance();
                       Transformer transformer = tf.newTransformer();
                       transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, validationPath);
                       transformer.transform(source, result);
                  catch(Exception e)
                       this.wrong(rowCount, 1, e.getMessage());
                       error = true;
             }Edited by: sarcasteak on Apr 13, 2009 1:33 PM

  • Supporting maxChars on editable ComboBox, string validator null out input once max is reached

    I have a ComboBox in a form set to editable, so it acts like a text input but as drop down values as well.
    The data here is required and I want to limit the number of characters that can be entered, normally under a TextInput control you would just set the maxChars.
    I have created a string validator, required is based on seletedLabel so that working as I would expect.
    I set a maximum character limit in the validator which does not limit the text but prevents validation if the count is over, so far so good.
    Now the issue, imagine you set this to 10 characters  maximum, type the 11th character the validator correctly invalidates the control and the standard message pops up and prevent form submission.
    But if the user is still typing as soon as you enter one character over the limit in this example the 12th character the input nulls out to empty string.
    I want to limit the the number of characters that can be typed or the validator to not null out, giving the user a chance to back space instead of clearing the input.
    Any ideas?
    TIA
    flash.

    I am probably missing something with all the scrolling up and down and back and forth, but I can't see how that line can throw an NPE. Or the constructor which it calls.
    What is the exact runtime message?

  • String.matches vs Pattern and Matcher object

    Hi,
    I was trying to match some regex using String.matches but for me it is not working (probably I am not using it the way it should be used).
    Here is a simple example:
    /* This does not work */
    String patternStr = "a";
    String inputStr = "abc";
    if(inputStr.matches( "a" ))
    System.out.println("String matched");
    /* This works */
    Pattern p = Pattern.compile( "a" );
    Matcher m = p.matcher( "abc" );
    boolean found = false;
    while(m.find())
    System.out.println("Matched using Pattern and Matcher");
    found = true;
    if(!found)
    System.out.println("Not matching with Pattern and Matcher");
    Am I not matches method of String class properly?
    Please throw some lights on this.
    Thank you.

    String.matches looks at the whole string.
    bsh % "abc".matches("a");
    <false>
    bsh % "abc".matches("a.*");
    <true>

  • Validating with multiple schemas

    I am setting the schama attribute as follow:
    String schemaSource = "C:\\Documents and Settings\\ayache\\My Documents\\C5 XML\\schema\\searhRequest.xsd";
                   String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
                   builderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource));searchRequest.xsd contains include statement: it referes to another schema. When i try to validate the xml document using the scheam above error is thrown stating that the elements that are defined in the second schema(BookingProfile.xsd) are not recognised or can't be resolved.
    Is there a way to set multiple schemas?
    Your help is much appreciated.

    I figured out my problem in case anyone else is having trouble..
    In the xml document that you need to refer to:
    xmlns:xsd="http://www.w3.org/2000/10/XMLSchema-instance that is the namespace
    supported by xerces 1.3.1.
    Whew!
    "Karen Schaper" <[email protected]> wrote:
    >
    Has anyone been successful at validating xml with a Schema running weblogic
    6.1
    sp2?
    Here is a snippet of code...
    SAXParserFactory objFactory = SAXParserFactory.newInstance();
    objFactory.setValidating("true");
    objFactory.setNamespaceAware("true");
    objFactory.setFeature("http://apache.org/xml/features/validation/schema",
    "true");
    objXMLInputParser.parse(new InputSource(new StringReader(XMLDocument)),
    A_HANDLER);
    When my xml code runs through the parser I get an error for each element
    saying
    the element type is not declared in the dtd or schema.
    Since weblogic 6.1 runs with 1.3.1 Xerces parser. Does it support xml
    validation
    with a Schema. From what I've read it seems that it does.
    Any help or insight would be appreciated.
    Thanks
    Karen

  • Drop down  ! check table validating ?

    Hi,
    For ALV edit mode i am creating a fieldcatalog-checktable field fill with value ! , then also while in the drop values are get validated with check table?
    It is validating the entry with checktable? why ? after giving  ls_fcat-checktable = '!'.
    * Here YDROP_DOWN field have check tabke values " ", 1, 2
      ls_fcat-fieldname = 'YDROP_DOWN'.    
      ls_fcat-datatype  = 'INT4'.
      ls_fcat-checktable = '!'.
      ls_fcat-no_out    = c_x.
      append ls_fcat to pt_fieldcat.
      describe table pt_fieldcat lines v_rows.
      call method cl_alv_table_create=>create_dynamic_table
        exporting
          it_fieldcatalog = pt_fieldcat
        importing
          ep_table        = g_hts.
      assign g_hts->* to <i_status>.
    Then during the first display
      call method g_grid->set_table_for_first_display
        exporting
          is_layout            = gs_layout
          i_save               = 'A'
          it_toolbar_excluding = i_exclude[]
        changing
          it_fieldcatalog      = gt_fieldcat[]
          it_outtab            = <i_status>[].
      call method g_grid->set_ready_for_input
        exporting
          i_ready_for_input = v_input.  " it will be 1 or 0

    Hi ARS,
    See the below link and i am sure it will help you lot
    /people/srilatha.t/blog/2007/04/16/alv-grid-150-insert-row-function
    /people/david.halitsky/blog/2007/04/24/so-youve-got-to-code-an-editable-alv-inside-an-sap-provided-exit-and-x-function-group
    Problem in ALV
    Thanks
    Seshu
    Message was edited by:
            Seshu Maramreddy

Maybe you are looking for