Trouble parsing string

I need to parse strings in the format "City State
Abbreviation Zipcode" (ie "Glenview, IL 60062") to seperate them as
their own variables. Problem is that sometimes there is a comma
after city, sometimes not, so I've resorted to REfind to seperate
the string. Here's the snippet, "city" is the entire string I
mentioned above. The problem is that the refind I use seems to be
returning 0. I'm trying to find the two capital letters that
designate the state abbeviation.
<cfif city neq ''>
<cfset crpos = refind("[:upper:][:upper:]",city) >
<cfset zip = trim(right(city,len(city)-crpos))>
<cfset citystate = trim(left(city,crpos)) >
<cfset newpos = find("#chr(32)#",citystate) >
<cfset state =
trim(right(citystate,len(citystate)-newpos)) >
<cfset actualcity =
trim(left(citystate,len(citystate)-newPos)) >
</cfif>

I probably should mention some explaination about what the
regular expression is doing:
Note: Groups are RegExp statements surrounded by ()
Group 1: Combination of Letters and Spaces (e.g. City Name)
optional comma and (required) space
Group 2: 2 Character upper case state code (State Code) (note
- depending on your source, state codes may not always be upper
case)
(required) space
Group 3: 5 digit string (e.g. Zip Code) (note - again,
depending on your source, you may be getting 5 digit zip + 4 or
even non-us zip codes that may involve alpha characters.)
The replace function is using back references to refer to the
text matched by group 1,2 and 3.

Similar Messages

  • Parsing String

    i have problem to parse string to document
    i have string like this str = "<root><data>1</data><data>2</data><root>";
    how to parse this string in docoment xml

    import java.io.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    public class PrettyPrinter {
       public static void main(String[] args) {
            // Assume filename argument
            String filename = args[0];
            try {
                // Build the document with SAX and Xerces, no validation
                SAXBuilder builder = new SAXBuilder();
                // Create the document
                Document doc = builder.build(new File(filename));
                // Output the document, use standard formatter
                XMLOutputter fmt = new XMLOutputter();
                fmt.output(doc, System.out);
            } catch (Exception e) {
                e.printStackTrace();
    }The above code is taken directly from
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom-p2.html
    u don't have to use Factories, this is what is said in that excerpt, it is very easy to use, and it is said that 80 % of the xml work can be done with 20 % or less work using JDOM.
    n joy ....
    </ksenji>

  • How to parse string to date in j2me?

    How to parse string to date in j2me?
    Please help me.

    Hi..
    String dyStr = "20";
    String mtStr = "1";
    String yrStr = "1999";
    Calendar cal = Calendar.getIntstance();
    int dy = Integer.parseInt(dyStr);
    int mt = Integer.parseInt(mtStr);
    int yr = Integer.parseInt(yrStr);
    cal.set(Calendar.DATE, dy);
    cal.set(Calendar.MONTH, mt);
    cal.set(Calendar.YEAR, yr);
    OK?

  • How could i parse string and link its model with my files in eclipse project?

    How could i parse string and link its model with my files in eclipse project?, as i read that we dont have to use standalone mode while working with eclipse projects.
    Example of what i want to do:
    I have file1.dsl in my project which contains some statements but the declaration of these statements are not in another file, i need to put them only in my code

    Hi Stefan,
    I have eclipse project contains 2 files, file1.dsl and file2.dsl, you can see the contents of the files below.
    file1.dsl contains some statements as shown below and file2.dsl contains the declarations of the variables. (like in C++ or Java we have declarations and usage)
    At this step file1.dsl and file2.dsl will be parsed successfully without any errors.
    Lets imagine that we will delete this project and will create another one and the new project will contain only file1.dsl (which contains the usage)
    At this step this file (file1.dsl) will contains some errors after parsing it, because we are using variables without declarations.
    So what i need is to parse the content of file2.dsl directly without adding this file to the project.
    I need to add the content of file2.dsl directly as a string in the code and parse it. just like that ( "int a;int b;" )
    And link file1.dsl with the model generated after parsing my string
    file1.dsl
    a++;
    b++;
    file2.dsl
    int a;
    int b;
    Thanks

  • Split Function unable to parse string correctly

    Hi,
    I'm using split function to split string into multiple rows using comma "," as delimiter. In a string I have following values which are not parsed correctly as they have comma inside the values. 
    American Dawn, Inc.
    Battalian USA, Inc.
    Fria USA, Inc.
    Lazer, Inc.
    Mexilink Inc.
    Is there any other approach to fix this issue?
    Here is the split function Im using:
    CREATE Function [dbo].[fnSplit] (
    @List varchar(MAX), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(MAX) NULL 
    As 
    Begin 
    Declare @item varchar(MAX), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final
    delimiter 
    Select @List = @List + @Delimiter -- get position of
    first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos
    -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List)
    - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    Another user in this forum posted a split function that
    he wrote:
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    Both of them are unable to parse above values incorrectly.
    FYI:  String is made of values that are selected
    by user in SSRS report. I think SSRS when combine values , put comma "," between multiple values.
    Any help or guidance would be appreciated.
    ZK

    duplicate of
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/820ac53c-ce25-4cc7-b828-5875a21d459d/split-function-unable-to-parse-string-correctly-in-ssrs-report?forum=sqlreportingservices
    please dont cross post
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Hi to parse String "x;y:z" in Core Java

    hi to parse String "x;y:z" in Core Java

    Deepak_A_L wrote:
    how do i parse a String "X;Y:Z" in java i.e the results of parsing the string
    String s = "X;Y:Z"
    in terms of ENGLISH LANGUAGE -->(X Semicolon Y Colon Z)
    should be the below o/p individual Strings.
    X
    Y
    Z
    how do i get the above output.????Split on a semi- or regular colon using String's split(String regex) method.

  • Trouble with Parsing String

    I am trying to take a string input from the command line and push it to an array then compare the array to another to see if there are any identical values. Here is the code in case it doesn't make sense.
    //  Parser.java
    //  PLCProject1
    //  Created by MilesB.
    //  Copyright 2007 . All rights reserved.
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class Parser {
    public static void main(String[] args)
              //Prompt the user to enter in String.
              System.out.println("Please enter in String to be tested");
              Scanner MyScan = new Scanner(System.in);
              String StringToTest = MyScan.next();
              char StringTestArray[] = new char[StringToTest.length()];
              int Array[] = {1,2, 3, 4, 5, 6, 7, 8, 9, 0};
              for(int j=0; j< StringToTest.length()-1; j++)
                        System.out.println(StringToTest + " ");
                        System.out.print(Array[j]);
              //open up standard input from CLI
              //BufferedReader ReadIn = new BufferedReader (new InputStreamReader(System.in));
              //StringToTest = ReadIn;
              //Testing the Entered String to see if it contains numeric values.
              for(int i=0; i< StringToTest.length()-1; i++)
                   for(int k=0; k< StringToTest.length()-1; k++)
                   if (StringTestArray[i] == Array[k])
                             System.out.println("This String contains numeric values");
                             break;
                   else
                   System.out.println("This Char is good");
                   System.out.println("This String was good");
    }

    ?

  • Parsing String to date

    This is my function to convert a string into a desired output format.But my Date in the desired output format is coming out to be null.Could smeone plz point out my mistake.
    Date getDateInDesiredFormat(String strInputDate,String strInputFormat,String strOutputFormat)
         try
           SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
           SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
           ParsePosition pos = new ParsePosition(0);
           Date dtInputDate=sdfInput.parse(strInputDate.trim(),pos);
           System.out.println(dtInputDate);
           String strFormattedDate=sdfOutput.format(dtInputDate);
           System.out.println(strFormattedDate);
           Date dtOutputDate=sdfOutput.parse(strFormattedDate.trim(),pos);
           if(dtOutputDate==null)
                System.out.println("dtOutputDate is null ");
           else
               System.out.println(dtOutputDate.toString());
           return dtOutputDate;
         catch (NullPointerException npex)
             return null;
          catch(Exception ex)
              return null;
       }This is how i am calling the function
    Date date=getDateInDesiredFormat("Fri Sep 30 20:30:56 IST 2006","EE MMM d HH:mm:ss ZZZ yyyy","MM-dd-yyyy");
      }

    You need to use the sdfInput object to parse the date and sdfOutput to format and print it (like you did before your 'if'):
    SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
    SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
    Date dtInputDate=sdfInput.parse(strInputDate.trim());
    String strFormattedDate=sdfOutput.format(dtInputDate);
    System.out.println(strFormattedDate);the toString() you use in the else block uses a default format, not the one you specify.

  • Parse String in OBIEE Answers.

    Please can someone help me to know how to parse a string in obiee answers:
    Eg: 'Administrators;XMLP_ADMIN;319'.
    I can do this very easy in Java but not sure how to do it in OBIEE. Appreciate your help
    Regards.

    Hi,
    what are you expecting to do with that string? can you be more specific?
    you want to have all values before the semi colon?
    you can use regexp in obiee to parse these kind of strings..
    i think this must be helpful to you..
    http://oraclebizint.wordpress.com/2009/06/04/oracle-bi-ee-10-1-3-4-1-handling-complex-string-manipulations-using-regular-expressions-regex-and-evaluate/
    if its helpful award points
    thanks,
    karthick
    Edited by: kart on May 28, 2010 3:56 PM

  • Parsing String in XML format

    Hello,
    What is the proper way to parse XML String instead of a XML file?.

    Use new InputSource(new StringReader(s)).
    Good luck.

  • Parsing String to XML Attribute bug

    Hello!
    I'm trying to convert String to org.w3c.dom.Document with javax.xml.parsers.DocumentBuilder, but when I check my XML Document after creating, I find that all the Attributes are like "" or "&#xa; ". Does anyone have some idea why that problem is and how it can be solved?
    Thanks a lot!
    Svigi

    There are lots of bug reports about Java 5's built-in XML parser screwing up on attribute values. Try forcing Java to use the current version of Xerces (download it) instead of whatever it has built in, if that seems to apply to you. On the other hand it's possible that the bug is in your code too.

  • Parsing String XML Document

    I didn't find a method that parses a XML document when it's not a file. I have a String that I want to parse and the method DocumentBuilder.parse only accepts a String that is a uri to a file.
    I write this code:
    String strXML = "<?xml version='1.0' ?><root><node>anything</node></root>";
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    domDoc = docBuilder.parse(strXML);
    Please gimme a light!!
    []'s
    Saulo

    I have a similar problem, I'm trying to do the same BUT in a servlet, it compiles and it actually works if I use it outside my servlet, but, when I mount the servlet with the code similar to this one here it doesn't read the string (at least that's what appears to be, because it doesn't writes to my DB as it should and it doesn't display anything as I'm specifying as my servlet response). Any help? I'm posting my code here:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.*;
    import org.apache.xml.serialize.*;
    import java.net.URLDecoder;
    import java.sql.*;
    import org.xml.sax.InputSource;
    import java.io.StringReader;
    public class SMSConnector extends HttpServlet
    //Public variables we will need
    public String Stringid;
    public String Stringpath;
    public String st;
    public int nid;
    //Servlet service method, which permits listening of events
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    //Initialization for the servlet
    ServletOutputStream salida = res.getOutputStream();
    ServletInputStream entrada = req.getInputStream();
    //Reading of the entering string
    BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
    res.setContentType("text/HTML");
    try {
    //Database handler
    Class.forName("org.gjt.mm.mysql.Driver");
    //DocumentBuilderFactory factory =
    //DocumentBuilderFactory.newInstance();
    //DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(lector.readLine()));
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc1 = docBuilder.parse(inStream);
    NodeList listasms = doc1.getElementsByTagName("sms");
    for(int s=0; s<listasms.getLength() ; s++)
    Connection Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/smsdb","root", "");
    Node nodosms = listasms.item(s);
    if(nodosms.getNodeType() == Node.ELEMENT_NODE){
    Element elementosms = (Element)nodosms;
    NodeList listatelf = elementosms.getElementsByTagName("tlf");
    Element elementotelf = (Element)listatelf.item(0);
    NodeList textTelfList = elementotelf.getChildNodes();
    String telefono = ((Node)textTelfList.item(0)).getNodeValue();
    //String SendingAddress = ((Node)textAddressList.item(0)).getNodeValue().trim();
    salida.println(telefono);
    NodeList listaop = elementosms.getElementsByTagName("op");
    Element elementoop = (Element)listaop.item(0);
    NodeList textOpList = elementoop.getChildNodes();
    String operadora = ((Node)textOpList.item(0)).getNodeValue();
    NodeList listasc = elementosms.getElementsByTagName("sc");
    Element elementosc = (Element)listasc.item(0);
    NodeList textSCList = elementosc.getChildNodes();
    String shortcode = ((Node)textSCList.item(0)).getNodeValue();
    NodeList listabody = elementosms.getElementsByTagName("body");
    Element elementobody = (Element)listabody.item(0);
    NodeList textBodyList = elementobody.getChildNodes();
    String body = ((Node)textBodyList.item(0)).getNodeValue();
    Statement sta = Conn.createStatement();
    sta.executeUpdate("INSERT INTO smstable (telf,op,sc,body) VALUES ('" + telefono + "','" + operadora + "','" + shortcode + "','" + body + "')");
    Conn.commit();
    Conn.close(); }
    //Catching errors for the SAX and XML parsing
    catch (SAXParseException err)
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    catch (SAXException e)
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    catch (Throwable t)
    t.printStackTrace ();
    }

  • DateFormat.parse(String)

    can anybody tell me why I don't get a SHORT format:
    import java.util.*;
    import java.text.*;
    public class MyDate{
       public static void main(String[] args){
          Date date = makeDate("04/22/2003");
          System.out.println(date); // what i get looks more like FULL
        public static Date makeDate(String dateString){
           Date date = null;
           try {
              DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
              date = fmt.parse(dateString);
          catch(ParseException e) {}
          return date;
    }Thank you.

    what I think is tripping you up is that a java.util.Date is not a String. It looks like you're thinking that you can format a java.util.Date object and somehow it is "11/23/2004" (or whatever) - but it's not - it's just a number. So, you have this String that you want to convert to a java.util.Date (which you correctly did with the parse method of the DateFormat class) but then you turn around and want to convert that java.util.Date to a String so you can put it into a List, so why not just put the original String into your List? Is it because you want to change the format? Fair enough, then you can use two DateFormat implementations, one to parse the incoming String to a Date, then the other to format the Date to the format you want. Or is it so you can do the sort chronologically? If that's the case, then you can write up a Comparator to do that, or you can store Dates in your list, sort them, and when it comes time to display this thing (if you ever do that) use a DateFormat implementation to convert those to a formatted String.
    Make sense?

  • Not able to parse string-xml through parseEscapedXml

    Hi all,
    What I am doing is, I am getting some data through polling and populating a schema variable. Because of having extra namespace in the resultant xml, I again used processXSLT and assigned the resultant xml to a string variable (after converting it to string).
    Now I want to pass this string to my web service. When I tried the
    ora:parseEscapedXML(ora:getContentAsString(bpws:getVariableData('niku_xog_project_write_xml_as_string')))
    It is giving the xpath error ORABPEL-09500. However when I remove the parseEscapedXML function, I am able to see the correct data on server. But it doesn't work because web-service expecting the xml instead of string.
    Below is the xml in string format. I picked it from server log.
    *<NikuDataBus><NikuDataBus>*
    *<Header version="12.0.1.5063" externalSource="NIKU" action="write" objectType="project"/>*
    *<Projects>*
    *<Project name="Web tech support" projectID="0066000000AAJFLAA5" description="The tech support calls are currently being handled in N America internally. Charter is trying to cut costs and the contact centers are high on the list. They are somewhat sceptical about moving the calls offshore, but are open to discussions about CR as a solution for web tech support. This account will most likely issue a RFP in late April or early May." >*
    *<CustomInformation>*
    *<ColumnValue name="client_name">Comcast Cable Holdings Llc</ColumnValue>*
    *<ColumnValue name="fa_sales_owner">John Harris</ColumnValue>*
    *<ColumnValue name="prj_category">Complex Deals</ColumnValue>*
    *<ColumnValue name="fa_offering_practice">BPO &amp; Call Center Services</ColumnValue>*
    *<ColumnValue name="fa_offering_category">BPO &amp; Call Center Services</ColumnValue>*
    *<ColumnValue name="fa_offering_type">Express Services - Complex Arrangement</ColumnValue>*
    *<ColumnValue name="fa_isales_stage">Qualifying Deal</ColumnValue>*
    *<ColumnValue name="probable_win">5</ColumnValue>*
    *<ColumnValue name="fa_delivery_location"/>*
    *<ColumnValue name="fa_contract_type">T&amp;M</ColumnValue>*
    *<ColumnValue name="prj_type">2</ColumnValue>*
    *<ColumnValue name="prj_classification">1</ColumnValue>*
    *</CustomInformation>*
    *</Project>*
    *</Projects>*
    *</NikuDataBus>*
    *</NikuDataBus>*
    What should I do?

    Tried this...
    <copy>
    <from expression="ora:parseEscapedXML(translate(bpws:getVariableData('niku_xog_project_write_xml_as_string')), '&amp;', '&amp;amp;')"/>
    <to variable="Invoke_2_write_project_WriteProject_InputVariable"
    part="body" query="/niku:WriteProject"/>
    </copy>
    still not working :(
    Getting this exception...
    <2009-08-13 16:55:24,796> <ERROR> <default.collaxa.cube.engine.dispatch> <BaseScheduledWorker::process> Failed to handle dispatch message ... exception ORABPEL-05002
    Message handle error.
    An exception occurred while attempting to process the message "com.collaxa.cube.engine.dispatch.message.invoke.InvokeInstanceMessage"; the exception is: Invalid xpath expression.
    Error while parsing xpath expression "ora:parseEscapedXML(translate(bpws:getVariableData('niku_xog_project_write_xml_as_string')), '&', '&amp;')", the reason is Parse Error in translate function..
    Please verify the xpath query "ora:parseEscapedXML(translate(bpws:getVariableData('niku_xog_project_write_xml_as_string')), '&', '&amp;')" which is defined in BPEL process.
    ORABPEL-05002
    Message handle error.
    An exception occurred while attempting to process the message "com.collaxa.cube.engine.dispatch.message.invoke.InvokeInstanceMessage"; the exception is: Invalid xpath expression.
    Error while parsing xpath expression "ora:parseEscapedXML(translate(bpws:getVariableData('niku_xog_project_write_xml_as_string')), '&', '&amp;')", the reason is Parse Error in translate function..
    Please verify the xpath query "ora:parseEscapedXML(translate(bpws:getVariableData('niku_xog_project_write_xml_as_string')), '&', '&amp;')" which is defined in BPEL process.
         at com.collaxa.cube.engine.dispatch.DispatchHelper.handleMessage(DispatchHelper.java:171)
         at com.collaxa.cube.engine.dispatch.BaseScheduledWorker.process(BaseScheduledWorker.java:70)
         at com.collaxa.cube.engine.ejb.impl.WorkerBean.onMessage(WorkerBean.java:86)
         at sun.reflect.GeneratedMethodAccessor38.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.ejb.interceptor.joinpoint.EJBJoinPointImpl.invoke(EJBJoinPointImpl.java:35)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.SetContextActionInterceptor.invoke(SetContextActionInterceptor.java:44)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.InvocationContextPool.invoke(InvocationContextPool.java:55)
         at oracle.j2ee.connector.messageinflow.MessageEndpointImpl.OC4J_invokeMethod(MessageEndpointImpl.java:297)
         at WorkerBean_EndPointProxy_4bin6i8.onMessage(Unknown Source)
         at oracle.j2ee.ra.jms.generic.WorkConsumer.run(WorkConsumer.java:266)
         at oracle.j2ee.connector.work.WorkWrapper.runTargetWork(WorkWrapper.java:242)
         at oracle.j2ee.connector.work.WorkWrapper.doWork(WorkWrapper.java:215)
         at oracle.j2ee.connector.work.WorkWrapper.run(WorkWrapper.java:190)
         at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExecutor.java:814)
         at java.lang.Thread.run(Thread.java:595)
    Pls help me.

  • Mastermind / Parse string with error handling ....

    Ok I am not going to hide the fact this looks like a homework question, honestly I already handed it in and now this is bothering me that I couldn't figure it out.......
    We had to make a mastermind client/server game only using text no graphical everything runs fine but how would one do error catching on this. (code posted below)
    Basically the user types in the command "guess r r r r" (guessing that the secret code is red four times ) and it parses it and assigns guess[] with the r and checks it based on the randomly generated color. The problem that I have is that is if someone makes a typo for example guess r rr r. How would one stop it from crashing from an out of bounds array request?
    if (command.matches("guess.*"))
                               int white = 0;
                               int black = 0;
                               String phrase = command;
                               String delims = "[ ]+";
                               String[] guess = { null, null, null, null, null, null, null };
                               guess = phrase.split(delims);
                               for (int i = 0; i < 4; i++)
                                    if (color.equalsIgnoreCase(guess[i+1]))
                             black++;
                        else if (color[i].equalsIgnoreCase(guess[i+1]))
                             white++;
                        else if (color[i].equalsIgnoreCase(guess[i+1]))
                             white++;
                        else if (color[i].equalsIgnoreCase(guess[i+1]))
                             white++;
                   if (black == 4)
                        anwser = "You WIN!!!!!!!! KIRBY DOES A SPECIAL DANCE FOR YOU \n (>'.')> (^'.'^) <('.'<) \n";
                        gamePlaying = false;
                        commandChecker = true;
                   else
                        turn++;
                        commandChecker = true;
                        anwser = "You got " + black + " black and " + white + " white it is your " + turn + " turn \n";
                   if (turn >= 10)
                        anwser = "You Lost =( , try again, the anwser was " + color[0] + color[1] + color[2] + color[3] + "\n";
                        gamePlaying = false;

    cotton.m wrote:
    if(guess.length!=4){
    // do something else besides evaluating the guesses. because something went wrong
    I should add that usually the best way of avoid array index out of bounds exceptions is to avoid ever hardcoding things like
    for(int i=0;i<4;i++)The 4 there is dangerous.
    It's safer to use the length
    for(int i=0;i<guess.length;i++)And the same applies to List(s) and the size method. Again usually that's a better idea but in your specific case anything more or less than 4 is not only a looping problem it would cause logical errors in the rest of your code... it is an exceptional case and should be dealt with specifically in your code.

Maybe you are looking for

  • How to set all file permissions to default?

    So a few background notes are in order. I came across an article on the NSA's website titled Hardening Tips for Mac OS x 10.6 "Snow Leopard", needless to say I have come to believe I have made this irreversible. The NSA suggested to do some fancy com

  • Need 2 find a way 2 connect external Firewire drive2only USB G3 iBook?

    my G3 Clamshell iBook only has a USB port and i need to connect my external Firewire Drive. can someone help me figure out how to do this? This iBook happens to be running 10.2.8 if it matters. Both my other Laptops are having their own big problems<

  • Pb block does not exist...

    In a pre_bind ops when the init program calls the sub function to trigger tests It does return me an error [13/Mar/2006:15:06:52 +0000] - ERROR<4187> - PBlock - conn=-1 op=-1 msgId=-1 - Internal error Trying to get a block element but the element ide

  • Is there a version of Battery Maximizer for the R40 running Vista 32-bit?

    I have an old R40 / 2896-GZU I recently upgraded to Vista and found the power management driver V1.67.xx.xx which I installed, but it seems to just be a low-level driver. I'd like to attempt to condition the battery as was possible with the "Battery

  • How to interrupt an funtion call and continue the followed code?

    for example, the code: public class A{ public static void main(String[] args){ int i = 0; method1(); system.out.println("exit"); public void method1(){ int j = 0; while(true){ j +=1; there is a error in method1(), so the call the method1( ) in main()