Trying to determine the last occurence of a number within a word string.

Hi All,
I am trying to find the last occurence of a number within a string. I have had a quick look at the Java Tutorial and know about lastIndexOf and substring. The thing is I have to test for the existance of the numbers 0-9 within a product code that typically looks like this:
s1_14G12B
s1_17G1BA
s2_24GD
The only part of the above strings that I am interested in is the letter(s) that follow the very last number, so in the case of those codes presented above, I would like to extract the following:
B
BA
D
I have written some code that performs a similar operation:
public class FindPriceCode
  private String priceCode;
  private String[] numberValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
  public FindPriceCode()
    priceCode = "s2_71G4BA";
    for(int i=0; i<numberValues.length; i++)
      int location = priceCode.lastIndexOf(numberValues);
System.out.println("Character " + numberValues[i] + " found at position: " + location);
public static void main(String[] args)
FindPriceCode myPriceCode = new FindPriceCode();
...finding the location of numberValues string within the given example code. I am now at a loss as to how I can determine the location of the last number occurence (moving right to left) and then build a substring from that number. Any help will be greatly appreicated.
Thanks
David

Hello,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CutNumberTest extends JFrame implements ActionListener {
     private JTextField input= new JTextField(10);
     private JTextArea result=new JTextArea(10,10);
     char[]numbers=new char[]{'0','1','2','3','4','5','6','7','8','9'};
     public CutNumberTest() {
          super("CutNumberTest");
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          JButton cutButton = new JButton("cut number");
          cutButton.addActionListener(this);
          JPanel topPanel=new JPanel();
          JLabel label=new JLabel("Please enter price-code:");
          topPanel.add(label);
          topPanel.add(input);
          topPanel.add(cutButton);
          getContentPane().add(topPanel, BorderLayout.NORTH);
          getContentPane().add(new JScrollPane(result));
          pack();
          setLocationRelativeTo(null);
     public void actionPerformed(ActionEvent e) {
          char[] code=input.getText().toCharArray();          
          int counter=code.length;
          boolean lastNumFound=false;
          while(!lastNumFound && --counter >= 0)
               lastNumFound=isNumber(code[counter]);
          result.append(lastNumFound ? "result: "+input.getText().substring(counter+1)+"\n" : "No number found!\n");
     private boolean isNumber(char chr){
          boolean isNumber=false;
          int counter=-1;
          while(++counter < numbers.length && !isNumber)
               isNumber=numbers[counter]==chr;
          return isNumber;
     public static void main(String[] args) {
          new CutNumberTest().setVisible(true);
}//copy/paste:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CutNumberTest extends JFrame implements ActionListener {
     private JTextField input= new JTextField(10);
     private JTextArea result=new JTextArea(10,10);
     char[]numbers=new char[]{'0','1','2','3','4','5','6','7','8','9'};
     public CutNumberTest() {
          super("CutNumberTest");
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          JButton cutButton = new JButton("cut number");
          cutButton.addActionListener(this);
          JPanel topPanel=new JPanel();
          JLabel label=new JLabel("Please enter price-code:");
          topPanel.add(label);
          topPanel.add(input);
          topPanel.add(cutButton);
          getContentPane().add(topPanel, BorderLayout.NORTH);
          getContentPane().add(new JScrollPane(result));
          pack();
          setLocationRelativeTo(null);
     public void actionPerformed(ActionEvent e) {
          char[] code=input.getText().toCharArray();          
          int counter=code.length;
          boolean lastNumFound=false;
          while(!lastNumFound && --counter >= 0)
               lastNumFound=isNumber(code[counter]);
          result.append(lastNumFound ? "result: "+input.getText().substring(counter+1)+"\n" : "No number found!\n");
     private boolean isNumber(char chr){
          boolean isNumber=false;
          int counter=-1;
          while(++counter < numbers.length && !isNumber)
               isNumber=numbers[counter]==chr;
          return isNumber;
     public static void main(String[] args) {
          new CutNumberTest().setVisible(true);
Regards,
Tim

Similar Messages

  • Determining the last archive applied on Logical Standby

    Hi,
    I am trying to determine the last log received and applied on my Logical Standby
    SQL> select thread#, max(sequence#) "Last Standby Seq Received"
    from v$archived_log val, v$database vdb
    where val.resetlogs_change# = vdb.resetlogs_change#
    group by thread# order by 1;
       THREAD# Last Standby Seq Received
             1                       14
    SQL> select thread#, max(sequence#) "Last Standby Seq Applied"
    from v$archived_log val, v$database vdb
    where val.resetlogs_change# = vdb.resetlogs_change#
    and applied='YES'
    group by thread# order by 1;
    Does not return anything
    These statements work ok on a physical standby.
    I know Sql Apply is enabled on my logical standby - my broker configuration is enabled and for the logical standby database, it is showing the Intended State as APPLY-ON with no Transport or Apply Lag on any of the databases
    Q. How do I determine the last seq applied on my logical standby ?
    thanks,
    Jim

    Hello;
    I have this from my notes:
    SELECT
      L.SEQUENCE#,
      L.FIRST_TIME,
      (CASE WHEN L.NEXT_CHANGE# < P.READ_SCN THEN 'YES'WHEN L.FIRST_CHANGE# < P.APPLIED_SCN THEN 'CURRENT' ELSE 'NO' END) APPLIED
    FROM
      DBA_LOGSTDBY_LOG L, DBA_LOGSTDBY_PROGRESS P
    ORDER BY SEQUENCE#;
    Best Regards
    mseberg

  • I am trying to determine the new project preset for multi-camera video shot as follows:  3 Canon camcorders, main shot is DV (tape) (720x480), b-roll is DVD (mini-disk) (720x480), additional b-roll is AVCHD (1920x1080).  Film is from a wedding, DV contain

    I am trying to determine the new project preset for a multi-camera video shot as follows:  3 Canon camcorders,
    Main shot is DV (tape) (720x480, 29fps) - ceremony and reception
    b-roll is DVD (mini-disk) (720x480, 29fps) - bride preparations
    additional b-roll is AVCHD (1920x1080, 29fps) - groom preparations and misc all day ceremony and reception. 
    Film is from a wedding, DV contains main footage so I assume it will need to be the base.  I am planning to use the preset for DV-Widescreen.  Is there a better option?  I'm concerned about playback as the three appear to have different PAR.  I'm using Premiere Elements 10 on W8.
    Ultimately this will be burned for two formats - one for a DVD that can be watched on a widescreen TV, second for a short clip trailer to go on vimeo.
    (And no I won't be doing this again for a wedding that I shoot.)

    VDRAVES
    Please review since I am not sure how you obtained Video 3 tall when you scaled Video 3 with Constrain Proportions in effect.
    Before
    After
    It becomes a zoomed in effect to get rid of the black borders. But, there is no tall and thin involved anywhere.
    And, after the Scale increase, you can always click on the screen and move the image around a bit
    (without overdoing it to get black borders again).
    After and an adjust
    Please let us know if you are OK with the information above.
    Thank you.
    ATR

  • How to determine the last transaction of a Batch Number

    Hello,
    For example,
    ITEMCODE - BATCHNUM - WHSCODE - LINENUM - DIRECTION
    ITEM1 - BATCH1 - WH1 - 0 - 0
    ITEM1 - BATCH1 - WH2 - 0 - 0
    ITEM1 - BATCH1 - WH1 - 1 - 1
    ITEM1 - BATCH1 - WH2 - 1 - 1
    How will I know that record number 4 is the last transaction regardless of the transaction type and warehouse code.  Is there any table which can help me solve this issue other than OIBT?
    Regards,
    Gilbert Ngo

    You could use the OINM Transnum (connected to the IBT1) to determine the last transaction:
    SELECT T1.[TransNum],
    T0.[ItemCode], T0.[BatchNum], T0.[WhsCode]
    FROM [dbo].[IBT1]  T0
    Join OINM T1 On T1.[BASE_REF] = T0.[BaseEntry]  and  T0.[BaseType] = T1.[TransType]

  • How to determine the "Last Value" in exception aggregation

    Hi gurus,
    I have a KeyFigure with an exception aggregation -Last value- by time.
    I report on a multiprovider ("containing" a infocube and a realtime infocube with BPS-InputLayout). I can correct separate Items with this BPS-Layout. So, at the end I have 2 values for one item.
    So, by these facts, my report shows the the last value for the specific KeyFigure, but I expected that both values (the value in the infocube and the correction via BPS)are sumed up.
    As this is due to the exception aggregation not the case, I could "overwrite" the normal value in the infocube with the BPS.
    But SAP determines the normal value in the Infocube as "Last Value", not the one in the correction cube, which is entered via BPS.
    How does SAP determine the "last value" as I can´t see any date...
    Thanks in advance!

    Thank you for your answer...
    I got the soltion by myself.
    I thought, Last Value means the last Value, depending on the time, but in my opinion the function last value should be called "Greatest Value".
    All figures with the same value for the reference characteristc are aggregated anyway.

  • I tried to update the last itunes, but the error message says there is a missing program to finish the update. But it doesn't tell what program.

    I tried to update the last itunes, but the error message says there is a missing program to finish the update, but it doesn't list what program is missing. I have never had issues in the past updating a new iTunes.

    "There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support perssonel or package vendor."
    That's perfect, thanks.
    Let's try the following user tip with that one:
    "There is a problem with this Windows Installer package ..." error messages when installing iTunes for Windows

  • HT201210 I continue to get an error 37 message when trying to restore my iphone 3GS which crashed after trying to upload the last update. Does anyone else have this problem?

    I continue to get an error 37 message when trying to restore my iphone 3GS which crashed after trying to upload the last update. Does anyone else have this problem?

    Did you manage to fix the issue?
    I have exactly the same issue as described above : I installed the update 5.1.1 on my iphone 3GS and since then, I can not turn it on anymore. In Itunes, I get an error 37 when I am doing a restauration and it stops.
    This error has nothing to do with firewall : I tried to restore the phone on several computers, including in an Apple reseller and it did not work anywhere.
    I spent several hours on phone with the hotline from Apple which arrived to the conclusion that it is a hardware issue, but the phone was working perfectly fine until I installed this update!

  • Determine the last date of visit before FY selected in the slicer

    Hi,
    I have data for date wise clients visits.  My objective is to determine the last date of visit to the client before the FY selected in the slicer.
    The objective, data layout and question is available in this file
    http://sdrv.ms/19RnW0A
    Please help with the appropriate PowerPivot calculated Filed formula.
    Thank you.
    Regards, Ashish Mathur Microsoft Excel MVP www.ashishmathur.com

    Hi, basically this calculation would solve your initial question, though, it does not match the requested results:
    LastVisit:=CALCULATE(MAX(Data[Date]), DATESBETWEEN(Calendar[Date], BLANK(), MIN(Calendar[Date])-1))
    its important to add that this calculation only works if you mark your Calendar-table as Date-table which was not the
    case in the sample workbook!
    assuming you select 2012-2013, then according to your Calendar-table you select dates from 31/12/2012 till 30/12/2013
    so the "last date of visit to the client before the FY selected in the slicer." would be the last visit before
    31/12/2012 which would be 12/12/2012 for Client A and not 25/02/2012 as expected result
    hth,
    gerhard
    Gerhard Brueckl
    blogging @ http://blog.gbrueckl.at
    working @ http://www.pmOne.com
    Gerhard's approach is a nice clean solution.
    The only thing I would add is that we could use LASTDATE and FIRSTDATE instead of the MIN/MAX functions:
    LastVisit:=
    CALCULATE(
    LASTDATE(Data[Date]),
    DATESBETWEEN(
    Calendar[Date],
    BLANK(),
    FIRSTDATE(Calendar[Date]) -1)
    In order to achieve the overall outcome described in the uploaded Excel workbook, changes to the how the [Financial Year] and [Financial Year Key] are calculated will also need to be made (so that the slicer filters the correct data ranges).
    This can be done by using the suggested calculated column changes above or something similar.
    Having reviewed the requirement again, the logic behind the [Last Visit Last Year] measure that I proposed is slightly different from what is required because it only looks at the last visit date
    within the previous financial year to the one currently selected in the slicer. On the other hand Gerhard's is looking for the last visit date
    any time before the first date in the selected financial year and this is more in-line with the actual requirement. With the provided dataset, both approaches provide the same outcome, but the difference
    in behaviour would become apparent if the last visit date was not found within the previous financial year to the one selected in slicer.

  • HT1386 I am trying to restore the last configuration I saved for my iPhone but iTune is asking for a password although I did not set any. What shall I do?

    I am trying to restore the last configuration I saved for my iPhone but iTune is asking for a password although I did not set any. What shall I do?

    No there's not.  Otherwise that wouldn't be very secure, would it?

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

  • Could not determine the year for TDS certificate number range

    Hello Experts,
    while i have configured TDS. now in order to post Invoice, i am getting error "Could not determine the year for TDS certificate number range".
    i have also mentioned/configured all parameters required for Certificate Numbering & assignment to Co. Code, TDS Tax Type/Code, etc
    please if someonce can help, how to clear this error & go ahead.

    Dear,
    Use transaction SM30. Enter J_1IINDCUS in table/view field and click on maintain. Press new entry tab and enter your company code. Just select "APRIL" in start month and save. This is basically a CIN setting.
    it should be solved................

  • When i use the apple tv it puts my computer to sleep.  the last time this happened i lost microsoft word with all the documents.  i'm asked to relaunch, but that step fails.  i'm frantic! can anyone help me see my documents again?

    when i use the apple tv it puts my computer to sleep.  the last time this happened i lost microsoft word with all the documents.  i'm asked to relaunch, but that step fails.  i'm frantic!  can anyone help me see my documents again? this also prevents me from reading attachments in my mail, since they are frequently launched in word.

    There's a whole lot to read in your post, and frankly I have not read it all.
    Having said that, this troubleshooting guide should help:
    http://support.apple.com/kb/TS1538
    In particular, pay attention to the mobile device support sections near the bottom, assuming you have already done the items above it.

  • Trying to get the last row from a resultset

    Hi,
    I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
    My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
    I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
    I've tried a variety of things and most seem to return the first row, not showing the updated values.
    Or, if it does work, it takes to long to load, and i get an error.
    here is the working code;
    Object m = machCBX.getSelectedItem():
    try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
    ResultSet.TYPE_SCROLL_INSENSITIVE,  //tried both INSENSITIVE and SENSITIVE
    ResultSet.CONCUR_READ_ONLY);
    last.setString(1, String.valueOf(m));
    rs. = last.executeQuery();
    if(rs.isAfterLast) == false ) {
    rs.afterLast();
    while(rs.previous()) {
    String p = rs.getString("part");
    int c = rs.getInt("count");
    partJTX.setText(p);
    countJTX.setText(c);
    }this grabs values, but they are not the last entered values.
    Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
    I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
    thanks
    -PD

    OK, you've got a major misunderstanding...
    The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
    Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
    In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
    While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course).

  • How to determine the last record inserted

    hi
    I have a table abc ( x number, y number, z date ) columns, there
    is no primary or unique key.
    I have been inserting values into it. there r some duplicate
    values to.
    but now I want to modify only the record inserted at the end.
    i.e
    if initially ABC is having
    x y z
    10 20 01-nov-2001
    11 20 01-nov-2001
    out of these records I want to change the value of x to 50 for
    the record which was inserted last or shall I say whose z is the
    greatest.
    I have been trying to do but what I see that the z column is not
    getting the time in increasing order. i.e even though I tried to
    display the dated in dd-mon-yyyy 24hh:mm:ss format still and I
    found that date is not consistant. the record I inserted first
    is have a much more value than the record I inserted last.
    please help...
    Sreekant

    rowid refers to the current position of the record; if the
    record has been moved (and there are any number of reasons why
    the database might shift a record) the order of rowid will not
    reflect the order of insertion.
    the only way to guarantee order of insertion is to timestamp the
    record. if I understand the original posting, you have been
    doing this.
    Now you should have been using SYSDATE. if you are saying that
    SYSDATE is giving you inconsistent results then you have a real
    problem: has somebody been tinkering with your database server -
    changing the system clock or something?
    Or are you using some other method to set the value for Z
    column? If so, what?
    rgds, APC

  • Trying to email the last 10 lines of a file in the body of an email

    Hi All:
    Total PS n00b here.
    I'm using PS 2.0 - I am using the "Get-Content | Select -last 10" on a logfile that I want to email. I got the email to work, but the formatting is lost (it's a Robocopy log that lists the details of what got copied/skipped/etc.)
    Is there a way to retain the formatting of the last 10 lines?
    Thanks for any feedback. 

    Thanks for the suggestions, everyone. I was able to get it closer using "Select-Object -last 10|%{"$_ <br/>"}. Remember, I'm using PS 2.0 & "-Tail" & "-last 10" wouldn't work w/out "Select-Object".
    I had a friend who had a PS script that does $msg.IsBodyHTML = $true and it got it closer.
    Here's what it supposed to look like outta Robocopy:
                   Total    Copied   Skipped  Mismatch    FAILED    Extras
        Dirs :       897         0       897         0         0        
    0
       Files :      8389      2877      5512         0         0      1396
       Bytes : 266.891 g 107.766 g 159.125 g         0         0 110.255 g
       Times : 109:33:28   6:35:33                       0:00:00   0:27:11
       Ended : Mon Jan 19 21:27:45 2015
    ===============================================================================
    And here's what I got:
    Total Copied Skipped Mismatch FAILED Extras
    Dirs : 897 0 897 0 0 0
    Files : 8389 2877 5512 0 0 1396
    Bytes : 266.891 g 107.766 g 159.125 g 0 0 110.255 g
    Times : 109:33:28 6:35:33 0:00:00 0:27:11
    Ended : Mon Jan 19 21:27:45 2015
    ==============================================================================
    I'd like to get the numbers to line up w/their columns & my manager says he prefers it in the body & not an attachment, but I tried tommymaynard's suggestions, but I don't know how to tell it to overwrite an existing file.
    Thanks again, all. I will make sure to push for installing PS 4, as it looks like there's more flexibility in it.

Maybe you are looking for