Counting strings

Hi, what i'm trying to do is to count how many times every possible three-word-string (in a logical order ie 1-3, 2-4, 3-5...) occurs in a file.
public class Blandning2 {
  public static void main(String[] args) throws Exception {
     String strang;
      int count = 0;
      int rakna = 0;
          Scanner sc = new Scanner(new File("test.txt"));
          Pattern p = Pattern.compile("\\b(\\w+)\\s+(?=(\\w+)\\s+(\\w+)\\b)");
              while (sc.findWithinHorizon(p, 0) != null) {
                  MatchResult m = sc.match(); 
                  count++;
               strang = m.group(1) + " " + m.group(2) + " " + m.group(3);       
               Pattern findstrang = Pattern.compile(strang);
                Scanner scc = new Scanner(new File("test.txt"));
                while (scc.findWithinHorizon(findstrang, 0) != null) {
                  MatchResult mandra = scc.match();
                  rakna++;
                   System.out.println("string number " + count + ": " + strang);
                   System.out.println("occurs: " + rakna + " times");
} the file it reads is looks like this:
Adam Bertil Cesar David
Erik Filip Gustav Helge
Ivar Johan Kalle Ludvig
Martin Niklas Olof Petter
Adam Bertil Cesar David
Erik Filip Gustav Helge
Ivar Johan Kalle Ludvig
Martin Niklas Olof
Adam Bertil Cesar David
Erik Filip Gustav Helge
Ivar Johan Kalle Ludvig
Martin Niklas
Adam Bertil Cesar David
Erik Filip Gustav Helge
Ivar Johan Kalle Ludvig
Martinmost strings should have occurrance of 4 but eg the string " Niklas Olof Petter" should only occur once. the output for the 18 first is:
idiom number 1: Adam Bertil Cesar
occurs: 4 times
idiom number 2: Bertil Cesar David
occurs: 8 times
idiom number 3: Cesar David Erik
occurs: 8 times
idiom number 4: David Erik Filip
occurs: 8 times
idiom number 5: Erik Filip Gustav
occurs: 12 times
idiom number 6: Filip Gustav Helge
occurs: 16 times
idiom number 7: Gustav Helge Ivar
occurs: 16 times
idiom number 8: Helge Ivar Johan
occurs: 16 times
idiom number 9: Ivar Johan Kalle
occurs: 20 times
idiom number 10: Johan Kalle Ludvig
occurs: 24 times
idiom number 11: Kalle Ludvig Martin
occurs: 24 times
idiom number 12: Ludvig Martin Niklas
occurs: 24 times
idiom number 13: Martin Niklas Olof
occurs: 26 times
idiom number 14: Niklas Olof Petter
occurs: 27 times
idiom number 15: Olof Petter Adam
occurs: 27 times
idiom number 16: Petter Adam Bertil
occurs: 27 times
idiom number 17: Adam Bertil Cesar
occurs: 31 times
idiom number 18: Bertil Cesar David
occurs: 35 timesthere were 56 hits which is only logical. i realize that with this method, it might print "Adam Bertil Cesar " aso several times (four in this case) but at this stage, this isn't a problem.
anyone who can see my mistake?
thank you in advance

I see two major problems with that code: the regex you're generating for the inner loop won't match if the whitespace within a three-name group is anything other than a single space character, and your hit-counter never gets reset. But that's a bad approach anyway. Instead of scanning the file over and over, you should scan it just once and use a Map to store the hit counts. import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Test
  public static void main(String... args) throws Exception
    Scanner sc = new Scanner(new File("test.txt"));
    Pattern p = Pattern.compile("\\b(\\w+)\\s+(?=(\\w+)\\s+(\\w+)\\b)");
    Map<String, Integer> counts = new TreeMap<String, Integer>();
    String current = null;
    int maxLen = 0;
    while (sc.findWithinHorizon(p, 0) != null)
      MatchResult m = sc.match();
      current = m.group(1) + " " + m.group(2) + " " + m.group(3);
      if (counts.get(current) == null)
        counts.put(current, 1);
      else
        counts.put(current, counts.get(current) + 1);
      maxLen = current.length() > maxLen ? current.length() : maxLen;
    int totalHits = 0;
    String spec = "%-" + (maxLen) + "s%3d%n";
    for (String key : counts.keySet())
      int hits = counts.get(key);
      System.out.printf(spec, key, hits);
      totalHits += hits;
    System.out.printf(spec, "Total hits:", totalHits);
}

Similar Messages

  • Idoc script function to count string

    Hi,
    Does anyone know if there is any build in function in idoc script to count the number of string.
    For example:
    A, B, C, D, E
    I want to count how many comma's are there using idoc script. If there is no build in function, what would be the best approach to achieve this.
    Many thanks.

    There is no built in function, but I would simply do this:
    <$rsMakeFromString("MyStringRS", "A, B, C, D, E")$>
    <$numCommas = MyStringRS.#numRows - 1$>
    Good Luck, and please award points as you see fit.

  • Counting strings row wise??

    Hi,
    I have report which has similar scenario as below.  I go u201Cfu201D in field and want to count number of u201Cfu201D occurs in each row.  If any row does not contain u201Cfu201D then it should return 0 (zero). If the row contains u201Cfu201D then I should count them.
    Any ideas please, how to count the numbers of u201Cfu201D in each row through crystal report formula?
    ID     A     B     C     D     Total
    1          f          f     2
    2               f          1
    3     f     f     f     f     4
    4                         0
    Edited by: GuroJee on Aug 11, 2010 4:40 AM

    Create a formula for your total. Something like this...
    IF {A} = "f" THEN 1 ELSE 0 +
    IF {B} = "f" THEN 1 ELSE 0 +
    IF {C} = "f" THEN 1 ELSE 0 +
    IF {D} = "f" THEN 1 ELSE 0
    HTH,
    Jason

  • How can i get a query to count a number of strings?

    I want the query to count for me how many holidays there are to the USA in my table. But im not sure how to get it to retreive the result of a string or varchar2 datatype. This is what i have tried so far.
    select count(COUNTRYVIS) <<this column contains all the countries visited
    from "IT220_HOLIDAYDETAILS" <<this is the table where the column is
    where COUNTRYVIS = "USA" << this is the result i want it to count
    ORA-00904: "USA": invalid identifier <<this is the error message im getting, is there a way to count strings?
    Thanks in advance!

    This has nothing to do with APEX. Please post basic SQL questions on the +{forum:id=75}+ forum.
    In any OTN forum, alll code should be posted wrapped in <tt>\...\</tt> tags as described in the FAQ:
    select count(COUNTRYVIS) -- this column contains all the countries visited
    from "IT220_HOLIDAYDETAILS" -- this is the table where the column is
    where COUNTRYVIS = "USA" -- this is the result i want it to countYou appear to be struggling with the distinction between identifiers and text literals. Hint: One uses double quotes, the other single quotes.
    Note that quoted identifiers are generally not a good idea.

  • Word Frequency Counter...

    Hello all, I am working on a project that is supposed to read in a text file from a command prompt, and then break all the words up. As the words are read in by the Scanner, I need to have a counter that counts the number of times the word has occured already that I can access and display in the output. I have come up with this so far as my driver/main class, and also the Count class that I'm trying to use to keep track of the number of times a word has occured in the text, and then so I can add it to a HashMap and display later... The problem is, whenever I try to run the program with a text file, it just ends up displaying all the words in a line and then a number 1 next to it. What I need is the output to look similar to this... For example,
    hello 1
    world 1
    Any help would be appreciated! Thanks.
       import java.io.*;
       import java.util.*;
        public class Driver{
           public static void main(String[] args){
             HashMap words = new HashMap();
             String nameOfFile = args[0];      
             File file = new File(nameOfFile);
             String wordd;
             Count count;
             try{
                Scanner scanner = new Scanner(file).useDelimiter(" \t\n\r\f.,<>\"\'=/");
                while(scanner.hasNext())
                   String word = scanner.next();
                   count = (Count) words.get(word);
                   if(count==null){
                      words.put(word, new Count(word, 1));
                   else {
                      count.i++;
                   System.out.println(word);
                 catch(FileNotFoundException e){
             Set set = words.entrySet();
             Iterator iter = set.iterator();
             while(iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                wordd = (String) entry.getKey();
                count = (Count) entry.getValue();
                System.out.println(wordd +
                   (wordd.length() < 8 ? "\t\t" : "\t") +
                   count.i);
    {code}
    {code}
    public class Count
         String word;
         int i;
         public Count(String inputWord, int increment)
              word = inputWord;
              i = increment;
    {code}
    Edited by: VisualAssassin on Apr 22, 2009 2:45 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    VisualAssassin wrote:
    Scanner scanner = new Scanner(file).useDelimiter(" \t\n\r\f.,<>\"\'=/");
    {code}According to the documentation for Scanner.useDelimiter(), the String supplied is used as a regular expression. Therefore, for the scanner to tokenize into two separate tokens, your input stream would have to contain all of those listed characters in order!
    Instead, use this (untested):
    {code}
    Scanner scanner = new Scanner(file).useDelimiter("[" + Pattern.quote(" \t\n\r\f.,<>\"\'=/") + "]+");
    The beginning and end square braces tell the regular expression engine to match +any+ of those characters, and the plus means one or more times.  The Pattern.quote is used to escape some of the characters that would get you into trouble because they have a special meaning in regexes, notably "."
    Edited by: endasil on 22-Apr-2009 11:43 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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.

  • MAPPING: Increment counter while creating destination structures

    Hello,
    i have the following source and destination structure:
    <src_struct> (0-n)
        <qualifier>
        <value>
    </src_struct>
    <dest_struct> (0-n)
        <counter>
        <qualifier>
        <value>
    </src_struct>
    only those dest structures have to be created where <qualifier="XX">.
    Thus my mapping on structure level looks like:
    if <qualifier>  equalS "XX" createIf --> <dest_struct>
    This works fine.
    But additionally i need to increment <counter> in the dest_struct. I.e., when i have 10 src_struct where 5 of them has <qualifier="XX"> i need 5 dest_struct with counter 1 to 5.
    I tried this with a UDF which has just a constant as input:
    "MY_COUNTER"  --> UDF:getNextCounter --> <counter>
    This argument is the name under which the last counter was saved in the global container. My expectation was that for each time the field <counter> will be created, my UDF reads the las counter, increments it, saves it back to the container and returns the result.
    but the bahavior is different:
    For example:
    if src_structures 6-10 have <qualifier>="XX" my UFD returns 6-10 in sequnce instead
    of 1-5. The shows me, that my UDF runs 10 times even though just 5 dest_struct are created.
    What do i wrong?
    Her my UDF:
    GlobalContainer gc  = container.getGlobalContainer();
    String counter = new String();
    counter  = (String)  gc.getParameter(MY_COUNTER);
    if(counter==null) {
         counter = "1";
         gc.setParameter(MY_COUNTER,counter);
         return(counter);
    Integer i_counter = new Integer(counter);
    int i = i_counter.intValue() + 1;
    Integer I = new Integer(i);
    counter = I.toString();
    gc.setParameter(ID_TYPE,counter);
    return(counter);

    Hi,
    Why dont you take qualifier as another argument (say b) for the same UDF.
    so that you can check the value of the qualifier and run the logic as you needed.
    as below,
    if (b.equals("XX"))
    GlobalContainer gc = container.getGlobalContainer();
    String counter = new String();
    counter = (String) gc.getParameter(MY_COUNTER);
    if(counter==null) {
    counter = "1";
    gc.setParameter(MY_COUNTER,counter);
    return(counter);
    Integer i_counter = new Integer(counter);
    int i = i_counter.intValue() + 1;
    Integer I = new Integer(i);
    counter = I.toString();
    gc.setParameter(ID_TYPE,counter);
    return(counter);
    Let me know if its not working.
    Hope this helps.
    Prasad Babu.

  • Binary I/O: Changing a String inside a Binary File

    Hi people, good morning!
    I have written a method here which takes two files as parameters. The method opens the first file (which may or may not be binary) using FileInputStream, loading it into a byte array. This byte array is converted to String by a CharsetDecoder (ISO-8859-1 encoding) and then i use indexOf() on this String to find the initial position of the token i need to find.
    Then, i transform the replaced token with getBytes() and insert it in the same position as the index found above, writing everything to the second file parameter as bytes to a FileOutputStream.
    The problem is that the destination file, when opened with the associated program (Eg: Oracle Forms Builder for *.fmb files) says the file is corrupt. Seeing that the original file opens and compiles normally, i believe the substitution process is corrupting the file.
    Do you know what my code below is missing? Strangely enough, when the replaced token is not larger than the original token, the file is not corrupted...
    Any help is greatly appreciated.
    Regards!
    Thiago Souza
              FileInputStream in = null;
              FileOutputStream out = null;
              try {
                   File f = new File(nameFrom);
                   in = new FileInputStream(f);
                   byte b[] = new byte[(int) f.length()];
                   in.read(b);
                   Charset cs = Charset.forName("ISO-8859-1");
                   CharsetDecoder cd = cs.newDecoder();
                   CharsetEncoder ce = cs.newEncoder();
                   byte[] headerChange = "$Header: MDBFNDENABLEEVENTS.fmb 115.1 2006/08/10 10:00:00 appldev ship $".getBytes();
                byte[] headerBytes  = "$Header: %f% %v% %d% %u% ship $".getBytes();
                   String header       = cd.decode(ByteBuffer.wrap(headerBytes)).toString();
                   int headerExcess      = headerChange.length - headerBytes.length;
                   header: for (int counter = 0; counter < 30; counter++) {
                        String fileContents = cd.decode(ByteBuffer.wrap(b)).toString();
                        int index = fileContents.indexOf(header);
                        if (index < 0) break header;
                         int headerEnd = index + headerBytes.length;
                         int endChunk = b.length - headerEnd;
                         byte[] initArray  = new byte[index];
                         System.arraycopy(b, 0, initArray, 0, index);
                         byte[] finalArray = new byte[endChunk];
                         System.arraycopy(b, headerEnd, finalArray, 0, endChunk);
                         b = new byte[b.length + headerExcess];
                         System.arraycopy(initArray, 0 , b, 0, index);
                         System.arraycopy(headerChange, 0 , b, index, headerChange.length);
                         System.arraycopy(finalArray, 0, b, headerEnd + headerExcess, endChunk);
                   } //Final FOR
                   out = new FileOutputStream(new File(nameTo));
                   out.write(b);
                   out.flush();
               } finally {
                    if (out != null) out.close();
                    if (in != null) in.close();
               }

    If the file is binary, converting it into a String is not a reversible operation and you will definitely get data corruption. You need to work directly in bytes.

  • Identify a character in a string .............

    An exercise of a text book of java.
    Count the number of letter 'a' appearing in a word. I can't do that. Here is my program, please help.
    import kenya.io.InputReader;
    import java.util.StringTokenizer;
    public class e47{
    public static void main ( String [] args ){
         System.out.println("Please type in a word ---->");
         String a = InputReader.readString();
         int r = countA(a);
         if (/*countA(a) == 0*/r == 0 ){
         System.out.println("There's no letter 'A' in this word.");
         else{
         System.out.println("The letter 'A' appears " + countA(a) + " times.");
    static int countA(String a){
              StringTokenizer letterA = new StringTokenizer (a);
              int acc = 0;
              while (letterA.hasMoreTokens()){
                   if ( letterA.nextToken() == "a"){
                   acc = acc + 1;
              return acc;
    Thanks a lot!!

    StringTokenizer parses "words" separated by a "token" such as a space, newline, tab, whatever. That's why it's not working for your purpose.
    Instead, try something like:
    int count = 0;
    for (int i = 0; i < a.length(); i++)
      if (a.charAt[i] == 'a')
        count++;
    return count;

  • Count the no of irritation in for each loop

    I want to count no of irritation in the for each loop container.
    Thank you for the help.

    If I were using C#, I would do something like that:
    First I would define another counter variable
    int anotherCounter=0;
    then, in for each loop I would parse your text by splitting from the pipe characters. If it matches the value I want, i simply increment the counter.
    string[] strColumnArr = strLine.Split("|".ToCharArray());
    if (strColumnArr.Length > 0)
    if (strColumnArr[1] == "myValue") anotherCounter++;
    smalkim - MCT, MCSD, MS, MCPS

  • Number of repeated characters in string array

    Hi,
    I m trying to get number of repeated characters in string array. I couldnt figure out where am i doing mistake.
    thank you,
    For example: count({"alpha, beta,"}, 'a')
    a is repeated 3
    l is repeated 1 etc.
    public class Test
    public static int count(String[] stringArray, char c)
    public String [] str = new String [2];
    int count = 0;
    str[0]
    str[1]
    for(int i = 0; i<str.length(); i++)
    if (str.charAt(i)
    count++;
    return count;

    There is a difference between a String and a String [].
    A String [] is an array of String class objects:/*  Traverse_Array_Of_Strings_1.java */
    public class Traverse_Array_Of_Strings_1
      public static void main(String [] argv)
        /* here is an array of Strings */
        String [] s = { "hello", "how", "are", "you" };
        int i, j;
        System.out.println("s.length = "+ s.length );
        for (i= 0; i < s.length; i++)
          System.out.println("s= <"+ s[i] +">");
          for (j= 0; j < s.length(); j++)
    System.out.print(s[i].charAt(j) +", ");
    System.out.println("\n-----");
    }output:java> javac Traverse_Array_Of_Strings_1.java
    java> java Traverse_Array_Of_Strings_1
    s.length = 4
    s= <hello>
    h, e, l, l, o,
    s= <how>
    h, o, w,
    s= <are>
    a, r, e,
    s= <you>
    y, o, u,
    Edited by: vim_no1 on Jul 15, 2010 7:43 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Count Up

    I need some help on code to just have numbers count up from
    100,000 to ?????? 1 count every 15 sec. THANK YOU -

    var timer:Number = 100000;
    var delay:Number = 15000;
    this.createTextField("my_txt", this.getNextHighestDepth(),
    10, 10, 100, 22);
    function count() {
    timer++;
    var comma:Number =
    Math.floor(Math.log(timer)*Math.LOG10E/3);
    var count:String = "";
    var my_str:String = String(timer);
    for (var i = 1; i<=comma; i++) {
    count = ","+my_str.substr(-3*i, 3)+count;
    count = my_str.substr(-3*i, 3)+count;
    _root.my_txt.text = count;
    setInterval(count, delay);

  • String array operations

    Hello. I am trying to implement a method which receives a string array called SCREEN and a string called DITHERED.
    I want to check how many CHARS from DITHERED are in SCREEN.
    When I try to compile I get "An illegalaccess exception ocurred. Make sure your method is declared to be public". Any help? THANKS
    class ImageDithering
        public int count(String dithered, String[] screen)
            int num=0;
            for(int i=0;i<screen.length;i++)
                for(int j=0;j<screen.length();j++)
    for(int k=0;k<dithered.length();k++)
    if(screen[i].charAt(j)==dithered.charAt(k))
    num++;
    break;
    return num;
    }Edited by: devesa on Aug 5, 2010 9:38 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    devesa wrote:
    Hello. I am trying to implement a method which receives a string array called SCREEN and a string called DITHERED.
    I want to check how many CHARS from DITHERED are in SCREEN.Well, the method you've chosen is just about as slow as it can be.
    A few questions:
    1. Which has more characters: 'dithers' or 'screen'?
    2. Do you know about StringBuilder?
    3. Do you know about [String.indexOf()|http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28int%29]?
    4. Have you thought about sorting your strings first?
    Winston

  • Can anyone tell me the difference between these String methods?

    There are methods that can convert a byte[] into string:
    String(byte[] ascii, int hibyte, int offset, int count)
    String(byte[] bytes, int offset, int length)
    String(byte[] bytes)
    I am now sticking on it. The first one runs great in my project, but it is deprecated. The remaining two return wrong answer I need. Can anyone expain what the difference between them? Really appreciate the help, thanks in advance.

    It seems like the first one translates each byte into one character. The other two use the default character encoding to translate possibly more than one byte into each character. Look up Unicode character encodings to understand the difference.

  • 1086  Syntax Error (on Counter.fla)

    Can anyone elaborate as to why I am getting an error with
    this "counter script" (counts down Years, Months, Days, Hours,
    Minutes, Seconds)? The error is "
    1086: Syntax error: expecting semicolon before months" (Line
    50), but after doing research on the error number and looking at
    the actual error line, it appears that it may be something other
    which I am not seeing?
    HERE is the Action Script I am using:
    this.addEventListener(Event.ENTER_FRAME,onEF);
    function onEF(evt:Event):void {
    var today:Date = new Date();
    var currentYear = today.getFullYear();
    var currentTime = today.getTime();
    var targetDate:Date = new Date(2011,10,16);
    var targetTime = targetDate.getTime();
    if (targetTime - currentTime > 0) {
    var timeLeft = targetTime - currentTime;
    } else {
    var timeLeft = currentTime - targetTime;
    var sec = Math.floor(timeLeft/1000);
    var min = Math.floor(sec/60);
    var hrs = Math.floor(min/60);
    var days = Math.floor(hrs/24);
    var months = Math.floor((H+L-7*M+114)/31);
    var years = Math.floor(days/365);
    sec = String(sec % 60);
    if (sec.length < 2) {
    sec = "0" + sec;
    min = String(min % 60);
    if (min.length < 2) {
    min = "0" + min;
    hrs = String(hrs % 24);
    if (hrs.length < 2) {
    hrs = "0" + hrs;
    days = String(days);
    if (days.length < 2) {
    days = "0" + days;
    months = String(months % 12);
    if (months.length < 2) {
    months = "0" + months;
    years = String(years);
    if (years.length < 2) {
    years = "0" + years;
    var counter:String = years + ":" months + ":" days + ":" +
    hrs + ":" + min + ":" + sec;
    time_txt.text = counter;
    }

    Thanks,
    kglad, for the quick and helpful response...
    I can't believe I didn't see that!
    Seems now I am getting another error on Line 22 -
    1120: Access of undefined property H, L, and M.
    Trying to correct that but if you have a better solution
    please feel free to share...
    Thanks again, regardless!
    A.J.

Maybe you are looking for

  • In acrobat 9 pro how do you fill a color in a picture?

    Hello Everyone, Does anyone know how to fill a color in a picture using Adobe acrobat 9 Pro. Lets say you have a picture in PDF format, that has a picture of a billboard, and that billboard is not really straight, kinda different shape, how could som

  • Duplicate catalog item; price editable

    Hi All, I have a client running SRM server 550; they have an issue that when a user creates a shopping cart and adds a catalog item, the price is not editable (as it should be). However, if the user then creates a copy that item, using the "duplicate

  • Built-in Firewall and Blocking of Dreamweaver

    When I turn on the automatic firewall in Sharing Preferences (OS 10.4.11) my uploads to a remote server through Dreamweaver MX are blocked. Is there a way to open the Firewall to allow these uploads? Thanks for any suggestions.

  • How to test if connection pool is set up correctly in WL 7 SP 7

    Hi all, 2 questions. 1) how do i test if the connection pool i set is working? in the testing tab of the jdbc connection pool in the console page, there is a Test Table Name, i entered 'dual' in the text field. After i clicked apply, there is no indi

  • Configuring profiles for transaction EXPD/AXPD and how the t-codes work

    Hello experts! I inadvertently ran across these transactions recently and (based on descriptions) want to explore its functionality further for my current client.  However, in their systems there is no Progress Tracking Profile configured, preventing