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.

Similar Messages

  • Parsing string with saxParser

    I've got my program ready to handle XML, but instead of parsing a file, I want to parse just a string.
    saxParser.parse( ???, handler);
    what should I pass in there?

    You should putnew InputSource(new StringReader(yourString))in there.

  • BPM  with error handling

    Hi,
    I have a BPM scenario as follows,
    Receive input file thru HTTP protocol
    Send it to SAP thru sync XI protocol
    Response from SAP has a field with status code
    If the code says its success, then send response back to 3rd party and place the input file in archive dierectory.
    If the code says its failed, then send an email with error description and plance the input file in error directory.
    I would like to have a breif hint on the step-wise process flow in BPM technically.
    Thanks,
    Karthik

    Thank you all.
    I would like to follow the solution suggested by Tarang Shah as below
    1. Receive step to receive the HTTP request
    2. sync send to send the data to SAP and get the response back
    3. then the switch where
    if status = 'OK' then
    1.async send --- to send rseponse to the directory u want
    2.async send ---here the message will be the one specified in step 1 which will go into Archive
    otherwise
    1.async send --- to send the mail using mail adapter
    2.async send ---here the message will be the one specified in step 1 which will go
    into ERROR folder
    Now my question is 'Do we need correlation in this case or will the refMessageID in the SAP response be internally correlated to MessageID of the request message in step 1?'
    Please clarify.
    Thanks,
    Karthik
    Edited by: Karthik Kaveriselvan on May 29, 2009 8:36 AM

  • Subcontracting with Error Handling

    Dear All,
    we have some subcontracting materials. If the warehouse do the good reciept and the one of the components is not at the subcontractor stock they get an error.
    Now they came up with the question if it is possible that this materials went to the COGI and once a week they solve this problems.
    kind regards,
    Bernhard

    Hi Bernhard,
    COGI is not enabled for this situation, and the reason I can think of is that the system is calculating online realtime the moving average price of the received material, by summing up the costs of the issued materials. Therefore the information on which and how much of the components were issued must exist at the time of receipt, and cannot be later processed like in COGI.
    I know this doesn't help with your problem, but at least now you can better explain to your users why the stock must be accurate.
    Regards,
    Mario

  • Powershell 4.0: Problem with error handling inside Eventhandlers - Powershell has stopped working

    Hallo!
    Please see the attached sample code. This code simply show a small WPF-Dialog.
    Test 1 (showing the problem)
    Simply run the program. You will see Powershell crashing "Powershell has stopped working".
    The cause of this is the devision by 0 inside the Eventhandler.
    We would normally expect, that the exception should be handled by the trap.
    Test 2 (showing normal operation)
    Simply remove the comment in line 28 ($i=1/0).
    This activates an exception outside the Eventhandler. Now the Trap will be executed normally.
    --> The exception can be handled by the Powershell Devloper.
    Can anybody help? Why does the Error management via Trap not work inside Eventhandlers?
    Thanks for some assistance and ideas!
    Regards
    Heike
    cls
    Set-StrictMode -Version 4.0
    $ErrorActionPreference = "stop"
    Add-Type -Assemblyname PresentationFramework
    # -- Eventhandler - will be fired during form load -----------------------------------------------------
    $FormLoaded = {
    Write-Host "EventHandler is running..."
    # Problem:
    # All exceptions will crash Powershell.
    # We would normally expect that the Global Trap will be executed!
    # This problem occurs inside of Eventhandlers only!
    # TEST 1 --> Create an Exception (Division by 0) --> Powershell crashes: "Powershell_ISE has stopped working"
    $i=1/0
    # -- End of Eventhandler----------------------------------------------------------------------------------
    # -- Start of Demo-Programm ------------------------------------
    Write-Host "Start Demo"
    # -- TEST 2 ---
    # Write-Host "Test 2: Testing Global Trap"
    # Create an Exception (Division by 0) --> Powershell does not crash --> Global Trap will be executed --> OK
    # $i=1/0
    # XAML-Code for WPF-Dialog
    [xml]$xaml = @"
    <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False" >
    <Grid Margin="0,0,0,-4">
    <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
    </Grid>
    </Window>
    $Form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml)) # Load form
    Write-Host "Register Event"
    $Form1.Add_Loaded($FormLoaded)
    Write-Host "Starting ShowDialog"
    $Form1.ShowDialog() > $null
    Write-Host "End of program"
    # Global Trap - all exceptions should be handled here
    trap{
    Write-host "Global Trap is running..."
    Write-host "End of trap - program will be stopped"

    It works fine if you don't try to execute the code while loading and if you use a better exception handling method.
    Add-Type -Assemblyname PresentationFramework
    [xml]$xaml=@'
    <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False" >
    <Grid Margin="0,0,0,-4">
    <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
    </Grid>
    </Window>
    $Form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml)) # Load form
    $Form1.Add_Loaded({
    Write-Host "EventHandler is running..."
    Try{
    $i=1/0
    Catch{
    Write-Host "$_"
    $Form1.ShowDialog()
    ¯\_(ツ)_/¯

  • LabVIEW for Mapping of Network Drives with Error Handling

    Is there a way to do the following easily in LabVIEW?
    - List drive letters and network paths of existing mapped drives on host PC
    - Check if a desired mapped drive is connected and if its disconnected reconnect to it
    - Receive related errors that may occur during attempting a connection to a mapped drive (i.e. path cannot be found, etc...)
    I know how to do most of this in VBScript but I'd like to avoid having ANY code for the work I'm doing be "non-G"!
    Thanks for your time!

    Hello Ray,
    You may want to take a look at the following Knowledgbase articles on NI.com
    How Does LabVIEW Find Which Disk Drives Are in My Computer?
    http://digital.ni.com/public.nsf/websearch/9DFF8F1788A7171A86256D10003776C0?OpenDocument
    How Can I Programmatically Map a Network Drive in LabVIEW on a Windows 2000/XP Machine?
    http://digital.ni.com/public.nsf/websearch/313C5E597B48652F86256D2700674EDB?OpenDocument
    Best Regards,
    Chris J

  • Parsing strings with Unicode values 16 bits

    How can I get the Unicode value for a character in a String when the value is greater than 16 bits?
    I need to extract a supplemental plane Unicode value from a string. However,  String.charCodeAt(index) truncates the Unicode value to 16 bits,  returning what should be 0x02F91A  as  0xF91A.  I see discussions that show that earlier versions of Flex stores such char codes as the two code points of a surrogate pair, but  in Flex 4, the string length is just 1 when I put only this character in the string.

    Does it work in JavaScript?  Could send it over via externalInterface.

  • Error Handling with OCCI

    Hi,
    is there any function available in OCCI to register user defined function with error handler, "just like RougeWave setErrorHandler"
    Thanks

    OCCI uses C++ exceptions (OCCI class SQLException) mechanism for errors. Can you please explain the error handler approach and its advantages?
    Thanks,
    Shankar

  • Error Handling in info-package strangely doesn't work

    Dear All,
    I'm trying to load master-data from R3 containing time-dependent attributes which, I know, are sometimes overlapping. As I still want to load the correct part of data, i've set Processing - via PSA and Error Handling - "Updating valid records, reporting possible" with number of errors more than the dataset itself. However, the load still fails and what is more interesting, all records in PSA are marked as "green" whereas the errors are reported in a log.
    And what makes me wonder even more is that the same info-package from the same DS is loaded in a test system OK - with errors handled and "trashed" in PSA and remaining updated in Info-Object MD.
    Does anybody can help to resolve this strange problem as i can't honestly see the difference in global settings of test and productive systems that could allow this...
    Thank you in advance

    Hi,
    Here you are extracting data for master data with one of the attribute as time dependent . So there are two more fileds are neccessary in extraction ,i.e, 'from date' and 'to date'.
    And it seems there is overlapping of this range for two records. Make sure it in PSA with record numbers. And make sure there will be no overlapping.
    With rgds,
    Anil Kumar Sharma .P

  • General Error handling

    I've managed to get myself confused with error handling in Forms 6i.
    If I have a trigger that does a 'commit-form' like this
    commit_form;
    IF NOT form_success THEN
    RAISE form_trigger_failure;
    END IF;
    EXCEPTION
    WHEN OTHERS THEN;
    END;
    and the commit_form fails due to a mandatory field being missing (or similar) then what happens first?
    Does my ON-ERROR trigger fire?
    Does the form_success check fail and raise form_trigger failure?
    Does my exception block get used?
    Or does more than 1 happen??
    I could - of course - find the answer to this through debug but I'm looking for a more generic answer if possible.
    Thanks - Sean.

    What happens first?  The forms validation process runs and informs user that the field is required.
    Does On-Error fire?  Yes, if you have one in your form.
    Does the form_success check fail and raise form_trigger failure?  Yes -- but ONLY if your On-error raises Form_trigger_failure.  If it does not, you have lots of problems.
    Does my exception block get used?  Yes.  Raising Form_trigger_failure causes control to pass to the exception handler.  But I never use an exception handler except when I code SQL commands.
    Now...  After commit_form, you should also check Form_Status.  Read the help topic on the Form_Success built-in.
    My standard C00_Commit program unit does this:
      COMMIT_FORM;
      IF :SYSTEM.FORM_STATUS <> 'QUERY'
      OR NOT FORM_SUCCESS THEN
        RAISE FORM_TRIGGER_FAILURE;
      END IF;
    END;

  • Error Handling: VI response to any error

    Hey guys,
    I need to make sure a piece of code executes whenever there is any error in the VI. I'm pretty new to Labview, and cannot wrap my head around "extracting" the errors, so I can pass them into an error handler... All I want, is for my code to find out that there is an error, take some action, and then stop execution.
    Any help is greatly appreciated, thanks!
    Solved!
    Go to Solution.

    You simply wire the error wire to the selector of a case structure. Click on file/new/from template/frameworks/SubVI with Error Handling
    =====================
    LabVIEW 2012

  • How to handle BEA-382108 error in route error handler?

    Hi,
    I have a proxy service with error handler at route level. when any wrong inputs are given to this proxy the Biz will generate fault with error as BEA-382108
    having error message as XPATH can only be done for XML or MFL content. This is error is handled by system error handler but not by route error handler.
    Can any tell me how to handle this error in route error handler...?

    In route Error Handler.
    Add If condition and add fn:contains($fault,"BEA-382108") in the if condition, and add your code/logic that you want to implement in case of this error in IF condiiton.
    Let me know if this helps.
    Regards,
    Karan

  • Subvi dll error handling

    Hi everyone
    I have a basic/principal question regarding subvi's and associated error handling.
    Say I have an DLL which contains a function that takes input a and b, outputs c and d and that I want to wrap this function call (plus additional logic) into a SubVI. I can imagine this done in two ways with error handling:
    Which one is the most "correct" (or pretty or smart) way to do it?
    Best regards
    Wuhtzu

    First off, I agree with nathand that you do not need the case structure (the Call Library Function Node handles it).
    Second, if you are wrapping DLL functions, take a look at the import DLL tool.  (Tools->Import->Shared Library in the menus).  It will create wrappers for your DLL functions -- then you just have to test them and make some tweaks
    For example, if you have a parameter which is a pointer, the tool will make you an input and an output (since it can't tell which it is meant to be, and might be both).  Often you really just want it as an input or just as an output, so you have to change that (and make sure, if an output, that you have someplace to put it; in some cases you will need to make a constant of that type and pass it into the Call Library Function node, and then pass it out.
    I have had a lot of success using this tool, and it saves a lot of repetetive grunt work.
    B.

  • Issue with SRDemo error handling

    Hi All,
    Glad the forums are back up and running. In debugging some error-handling issues in our own application, I found an issue in the error handling code of SRDemo. I thought I'd post the issue here, as many of us (myself included) use some SRDemo code as the basis for our own applications.
    The issue can be found in the oracle.srdemo.view.frameworkExt.SRDemoPageLifecycle class, specifically in the translateExceptionToFacesErrors method. I'll show the code that has the issue first, and explain the issue afterwards:
            if (numAttr > 0) {
                Iterator i = attributeErrors.keySet().iterator();
                while (i.hasNext()) {
                    String attrNameKey = (String)i.next();
                     * Only add the error to show to the user if it was related
                     * to a field they can see on the screen. We accomplish this
                     * by checking whether there is a control binding in the current
                     * binding container by the same name as the attribute with
                     * the related exception that was reported.
                    ControlBinding cb =
                        ADFUtils.findControlBinding(bc, attrNameKey);
                    if (cb != null) {
                        String msg = (String)attributeErrors.get(attrNameKey);
                        if (cb instanceof JUCtrlAttrsBinding) {
                            attrNameKey = ((JUCtrlAttrsBinding)cb).getLabel();
                        JSFUtils.addFacesErrorMessage(attrNameKey, msg);
                }Now, this bit of code attempts to be "smart" and only show error messages relating to attributes if those attributes are in fact displayed on the screen. It does so by using a utility method to find a control binding for the attribute name. There are two issues with this code, one obvious, and one that is a bit more subtle.
    The obvious issue: if there is a binding in the page definition, it doesn't necessarily mean that the attribute is shown on the screen. It's a good approximation, but not exact.
    The other issue is more subtle, and led to errors being "eaten," or not shown, in our application. The issue comes if you are using an af:table to display and update your data. In that case, the findControlBinding will not find anything for that attribute, since the attribute is contained within a table binding.
    Just posting this as a word to the wary.
    Best,
    john

    somehow, this message got in the wrong thread....
    Hi Frank,
    Yes, I simply scripted it out this way to contrast the behaviour if the first attribute was read-only vs not read-only. I found the issue on a page in our app that was simply drag-and-drop the VO from the data control on the page.
    It's quite annoying, because our particular use case that hit this error is a "save" button on the page. If the commit operation doesn't return any errors (and it doesn't in this use case!), we add a JSF message saying "save successful" - then the attribute errors are further added later in the page lifecycle, so we get 3 messages: "Save successful" and "Fix this error" and "Tried to set read-only attribute" - quite confusing to the end-user when the only message they should see is "fix this error."
    At any rate, the fix is to simply re-order the attributes in the page definition - that doesn't affect the UI at all, other than to fix this issue.
    John
    it was supposed to be something like:
    Hi Frank,
    Thanks for the reply. I was simply posting this here so that people who use the SRDemo application techniques as a basis for developing the same functionality in their own apps (like me) can be aware of the issue, and avoid lots of head-scratching to figure out "what happened to the error message?"
    John

  • Problem in error handling in SAX Parser

    My application takes xml message as input.
    If a error was found while validating, an <Errors> <Error></Error></Errors> element is included in the orginal message and send back to the user.
    While validation xml message I found an interesting problem.
    Created a false entry for the root element attribute.
    Traced method invocation.
    First the call back error method is invoked,then the start element(stored the attributes inside the starElement to a instance variable).When i tried to print the attribute .As the error method got invoked first
    if showed "null".
    But when i created the same case with the child elements attributes
    even though invoking of the methods happens in the same sequence
    attributes got assigned and can print the attibutes values.
    xml is schema vaidated .Is there any restriction that root element should not contain attributes.Can any one explain how the call back methods are invoked .
    Regards
    Dheeraj
    // import statements here
    public class OperationHandler extends DefaultHandler {
         private static Logger logger = Logger.getLogger(OperationHandler.class.getName());
         private Attributes attributes;
         private StringBuffer dataStore;
    public OperationHandler() {
    dataStore = new StringBuffer(100);
         * Receive notification of the end of an document.
         public void startDocument() {
              logger.debug("OperationHandler: startDocument");
         * Receive notification of the beginning of the element.
         public void startElement(String uri, String lName,
                                            String qName, Attributes attributes) {
              logger.debug("OperationHandler: startElement" + lName);
              dataStore.setLength(0);
         * Receive notification of the end of an element.
         public void endElement(String uri, String lName, String qName) {
              logger.debug("OperationHandler: endElement");
              // bussiness specific code
         * Receive notification of the end of an document.
         public void endDocument() {
              logger.debug("OperationHandler: endDocument");
         public void error(SAXParseException saxe) {
              logger.debug("OperationHandler : error");
              System.out.println("CurrentElement"+currentElement +" "+"Attributes" + attributes);
                   if(attributes != null) {
                        for(int i=0; i < attributes.getLength(); i++) {
                             System.out.println(saxe.getColumnNumber());
                             System.out.println(saxe.getLineNumber());
                             System.out.println(saxe.getMessage());
         public void fatalError(SAXParseException saxe) throws SAXException {
              logger.debug("Fatal error while parsing message");
              logger.error("Error " + saxe.getMessage() );
         public void warning(SAXParseException saxe) throws SAXException {
              logger.warn("Warning " + saxe.getMessage() );
         * Receive notification of character data inside an element.
         public void characters(char[] charData,int start, int length) {
              String strData = new String(charData, start, length);
              if(strData != null) {
                   strData.trim();
                   dataStore.append(strData);
    }

    Hi Muruganand,
    Is the data load failing while loading data or while activating?
    if the data load is failing at activation, thers is nothing you can do except editing the records in PSA and then update them.
    As far as i have seen, the data load to DSO fails in Activation and not while loading. this is the reason why the records are not collected in error stack
    unlike if it is a cube, the data load fails while loading collecting the recods in error stack.
    hope this helps,
    Thanks and Regards,
    Srinath.

Maybe you are looking for

  • Suggested data file size for Oracle 11

    Hi all, Creating a new system (SolMan 7.1) on AIX 6.1 running Oracle 11.  I have 4 logical volumes for data sized at 100gb each.  During the installation I'm being asked to input the size for the data files. The default is "2000mb/2gb" is this accept

  • Youtube Video in iWeb "html Snippet" is Blank?

    The html Snippet Widget shows an unhappy face icon when I publish the site to the internet in preview form. In iWeb itself the video shows up as a blank box on my site when I load the "embed" text from the Youtube video into the black box window and

  • Changes not saved when I open Firefox

    I just had to get a new modem, and now when I start Firefox, my personal is gone. I also have speed dial and anything I've added to it is also gone. Any help would be appreciated!!

  • ERROR:Simulator:861 - Failed to link the design

    hi i'm a very new student user of xilinx 14.2 design tool who just used it 2 weeks. this week i should do "Simulate Behavioral Model" but i can't.... just i saw below messages.. and i don't know what is the matter. Started : "Simulate Behavioral Mode

  • Another App Store bug?

    I downloaded, long time ago, a free version of WhiteNoise, then the app became shareware. Today I got a message from AppStore telling me it was updated but if I try to download it, either from mac or iphone, I get the error "item is no more available