UDF to remove chars!

Hi,
I need to remove the last three characters of a given string  It should be for the entire queue.
Let me know the udf for this as I assume it can't be achieved using standard functions.
Regards
Anandh

Hi,
Try with
return str.substring(0,str.length()-3);
Thanks
Anand

Similar Messages

  • Remove char(160) and space in SSIS

    Hi everyone,
    I'm using SSIS package to import from excel source to SQL db , before do that, i want to remove all space and char(160) if any .
    But with this : REPLACE(REPLACE(APP_ID_TRANSACTION,"& chr(160)","")," ","") , i can only remove space , cant remove char(160) .
    Any ideas for this ?
    Many thanks,
    Hong

    Hi, with excel i can use this :=SUBSTITUTE((SUBSTITUTE(C2,CHAR(160),""))," ","") , to remove all of space on any field, but in SSIS, i still cant remove char(160) ..
    Pls help me..

  • Reading a string and remove chars

    Hi,
    I am new the java and I am having a problem with converting a string to an int. I have a data comming in to gbyte_in which is "1;1;1". I am then converting it to a string a spliting it up into three vars to hold each value. I am then converting the string to a int so I can use it. The problem comes when I try to convert the last value as I get a
    numberformatexception, I think there must be some chars such as Enter or line feed at the end causing the problem. I have tried using the gstr_string.replace('\n',' ') but still having the problem.
    I have put a basic example of what I am doing below, If someone could help a beginner with understanding what I am doing wrong I would be very greatful
    Thanks
    Joolz
    ** Start code**
    byte[] gbyte_in;
    private void CheckData_In()
    int i;
    /* make STRING of BYTE */
    String lstr_temp = new String(gbyte_in);
    /* take STRING a make an INT*/
    i = Integer.parseInt(lstr_temp);
    ** End code **

    Hi,
    I have,
    this is what comes in 1;2;3
    I can convert 1 and 2 to an int but 3 throws the error, I am just doing a substring looking for the ";". So I think there must be some special chars at the end, but I cannot find a way of removing them before I convert it to an int.
    Thanks
    Joolz

  • Help removing char from midpoint of string using deleteCharAt()

    How do you properly remove a char from a String at its midpoint? My attempt is on Line 80 and it does not want to work.
    I am using [http://java.sun.com/j2se/1.3/docs/api/java/lang/StringBuffer.html|http://java.sun.com/j2se/1.3/docs/api/java/lang/StringBuffer.html] as a reference for deleteCharAt()
    Am I on the right track or should I try something else?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Palindromes extends JFrame implements ActionListener
         JPanel centerPanel = new JPanel();
         JLabel enterDataLabel = new JLabel("  Enter a word or phrase with no punctuation: ");
         JTextField enterDataField = new JTextField(15);
         JLabel displayLabel = new JLabel("");
         JLabel spacer = new JLabel("");
         JButton submitButton = new JButton("Check");
         JButton clearButton = new JButton("Clear");
         public static void main(String[] args) throws IOException
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch(Exception e)
                   JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
              Palindromes f = new Palindromes();
               f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
             f.setSize(300,120);
               f.setTitle("Playing with Palindromes");
               f.setResizable(false);
               f.setVisible(true);
         public Palindromes()
              Container c = getContentPane();
              c.setLayout((new BorderLayout()));
            centerPanel.setLayout(new GridLayout(6,1));
                   centerPanel.add(spacer);
                   centerPanel.add(enterDataLabel);
                   centerPanel.add(enterDataField);
                   centerPanel.add(displayLabel);
                   centerPanel.add(submitButton);
                   centerPanel.add(clearButton);
                   submitButton.addActionListener(this);
                   clearButton.addActionListener(this);
                   c.add(centerPanel, BorderLayout.CENTER);
                   addWindowListener(
                         new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                                    int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Palindromes", JOptionPane.YES_NO_OPTION);
                                     if (answer == JOptionPane.YES_OPTION)
                                          System.exit(0);
         public void actionPerformed(ActionEvent e)
               String arg = e.getActionCommand();
              if(arg == "Check")
                   String word = enterDataField.getText();
                   int wordSize = word.length();
                  int midpoint = wordSize/2;
                   deleteCharAt(midpoint);
                   StringBuffer lastHalf = new StringBuffer(word.substring(midpoint));
                   StringBuffer firstHalf = new StringBuffer(word.substring(0,midpoint));
                   if (lastHalf == firstHalf)
                        displayLabel.setText(word + " is a palindrome!");
                   else
                        displayLabel.setText(word + " is NOT a palindrome!");                    
              if (arg == "Clear")
                   enterDataField.setText("");
                   displayLabel.setText("");
    }

    Looce wrote:
    80 |               deleteCharAt(midpoint);
    82 |               StringBuffer lastHalf = new StringBuffer(word.substring(midpoint));
    83 |               StringBuffer firstHalf = new StringBuffer(word.substring(0,midpoint));line numbering courtesy of GNOME's text editor(replying to self)
    deleteCharAt is an instance method of StringBuffer, so you need to have one to work with. Suggestion: drop lines 82/83 and use String result = new StringBuffer(word).deleteCharAt(midpoint).toString();

  • Substring from certain location and removing chars.

    Hello!
    1.
    I have many Strings like these:
    "apple,trees, water, money, 150 m, 90 000 EEK, 3 421.79 EEK/m"
    "dogs, cats, beer, water, metal, roads, 35 000 000 EEK, 27 888.45 EEK/m"
    How do I get these substrings - "90 000" and "35 000 000"? I cannot determine the starting position of these substrings.
    2. How do you remove specific characters from a string?
    For example, I have string "35┬Ā000┬Ā000┬Ā". I want to get string like this
    "35000000".
    Any help is greatly appreciated.

    Yes, the trailing EEK identifies the substring. I
    would be very grateful if somebody tells me how to
    remove these chars now.It is still not clear to me. Do you mean you want to end up with
    "apple,trees, water, money, 150 m"
    "dogs, cats, beer, water, metal, roads"
    or do you mean you want to extract the value i.e.
    90 000 EEK and 3 421.79 EEK/m
    35 000 000 EEK and 27 888.45 EEK/m
    ?

  • Reg: UDF for removing values after decimals

    HI,
      Please help me on the below issue,
      I need an UDF for the follwing requirement,
    as my input value is 12354.12354875 then the result will be like 12345.123,
    After deceimal it should get only 3 values.
    Please help me points will be awarded.
    Edited by: UDAY on Apr 5, 2010 3:56 PM

    >
    UDAY wrote:
    > yes its needed to be truncated only not rounded.
    In that case even the standard function FormatNum can also help.
    Regards,
    Abhishek.

  • Fm to Remove chars from tel num

    Is there a function module that will delete all special characters and non numeric characters from a telephone number?

    Hi ,
    This can be easily achieved using a logic.
    compare the given data with the string '0123456789'  and ifin comparison you find anything apart from this delete this value.
    Sample logic
    m_valid = '0123456789'
      m_strlen = STRLEN( phone_number ).
      DO m_strlen TIMES.
        m_char = phone_number+m_pos(1).
        IF m_valid NS m_char.
          phone_number+m_pos(1) = ' '.
        ENDIF.
        m_pos = m_pos + 1.
      ENDDO.
    after this condense ur string to remove the spaces.
    Regards,
    Anuij

  • Removing chars in Strings

    Is there a way to remove a character in a String? I have an assignment where I made a calculator, and I'm using a switch that converts an integer into a string for storage depending on the button pushed, and then back into a double when it's called. But I'm having trouble removing the "-" for negative values. Is there any way to remove a known character or do I have to convert the string to double, remove the negative and then convert back to string to store it?

    hi,
    you can try it that way...
    I guess the '-' appears only at the beginning =P
    if( yourString.indexOf('-') != -1 ) //'-' found
      yourString = yourString.substring(1,yourString.length());Hope this helped
    cu Errraddicator

  • Removing Leading And trailing Zeros

    Hi Guys ,
    Can You help me out in UDF for removing leading and Trailing zeros
    Ex :  0123.234000000
    And it must satisfy below conditions .
    1 ) If value as Null we need 0.0 in target
    2) if the value is 0.0 we need 0.0 in target
    Thanks in Advance

    One more option:
    Input will be "str" of type string.
    Execution type: single value.
    mapping:
    Input -> mapwithdefault(0.0)->UDF->output
    if( !str.equals("0.0"))
    char[] chars = str.toCharArray();
    for (int index=0; index < str.length();index++)
    if (chars[index] != '0')
    str =str.substring(index);
    break;
    int length,index1 ;
    char[] chars1 = str.toCharArray();
    length = str.length();
    index1 = length -1;
    for (int in1=index1-1; in1>0;in1--)
    if (chars1[in1] != '0')
    str=str.substring(0,in1+1);
    break;
    return str;
    else
    return "0.0";
    http://wiki.sdn.sap.com/wiki/display/Java/RemoveLeadingandTrailingZerosfroma+String

  • Creating a UDF in SAP XI

    Hi,
    I have Idoc to File Mapping in SAP XI, where I need to populate "Spaces" in most of the Target fields Dynamically. I need to create a UDF for this mapping. Since I have n no.of Target fields where I need to populate Sapces and Target fileds has different lengths. As of now I have cretated a simple UDF which is usefull only for one field mapping. Below is the UDF:
    String s;
         char []c = new char[10];
         for(int i=0; i<10; i++)
            c<i> = 'S';
         s = new String(c);
         return s;
    2. My source file will be having 1000 records where 999 records will be mapped to Traget sturucture and the end of the Record should be mapped to the other Traget structure(Traget sturcture is same in the both the cases).
    Please let me know how can I go about on this.
    Thanks in Advance.
    Jose

    Hi Joseph,
    Give a try to use the below UDF for the fields where you want to have some hardcoded values :
    a : Field you would like to change
    b : New hardcoded value for the field.
    for( int i=0; i<a.length; i++)
      if (i==(a.length-1))
          result.addValue(b[0]);
      else
         result.addValue(a<i>);
    input_field_1   --------------------
                                           UDF  -------------------- target_field_1
    new_constant_EOD  ------------------
    Rest all mappings should remain as it is.
    Let me know if you face any issue.
    Thanks,
    Pooja

  • UDF doesn't work in output

    Hi
    I use a UDF to remove leading zeros from an alphanumeric string. When I test it in the Message Mapping, it works fine. But when the output comes, it's not removing zeros, in SXMB_MONI
    What possibly could be the reason ?
    Regards

    Bhavesh
    FORMATNUM won't work. It's alphanumeric string. It will fail
    Raja
    I have activated Message Mapping. Cache refresh as in SXI_CACHE, complete cache refresh? I just did that and it says cache started in background. How long will it take to complete?
    Regards

  • Help:FileWriter gives no output

    Hi:
    The following code gives no errors but also no output. I know that the encrypt method works because I am able to print the output to screen but I cannot get FileWriter to work.
    Can someone help me with this problem?
    Thanks.
    import java.io.*;
    class Monoalphabet
      public static void main(String args[])
      String keyword = args[0];
      char [] cypher;
      cypher = makeCypher(removeDups(keyword));     
      try
       FileReader f = new FileReader(args[1]);
       FileWriter f1 = new FileWriter(args[2]);
       encrypt(f,f1,cypher);
        catch(Exception e)
          System.out.println("Exception: " + e);
      public static void encrypt(FileReader reader,FileWriter writer, char[] cypher )
         int positionOfA = 'a';
         String outgoing = ""; 
         String temp = "";
         BufferedReader infile  = new BufferedReader(reader);
         try {
         while(( temp = infile.readLine()) != null)
              for (int k = 0; k < temp.length(); k++)
              char whatever = temp.charAt(k);
              char ch = cypher[(int)whatever -  positionOfA];
              String chs = new Character (ch).toString();
               outgoing = outgoing + chs;
               System.out.println(outgoing);    
             writer.write(outgoing);   
        catch(Exception e)
          System.out.println("Exception: " + e);
      public static String removeDups(String keyword)
      { String keep = "";
        keyword = keyword + "zyxwvutsrqponmlkjihgfedcba";
       for(int i = keyword.length()-1; i > -1 ; i--)
       if(i == keyword.indexOf(keyword.charAt(i)))
        keep = keyword.charAt(i)+ keep;
        return keep; 
      public static  char[] makeCypher(String remove)
          char Array [];
          Array = remove.toCharArray();
          return Array;

    You may want to try flushing your FileWriter when you are done.
    FileWriter f1 = null;
    FileReader f = null;
    try {
       f = new FileReader(args[1]);         
       f1 = new FileWriter(args[2]);  
       encrypt(f,f1,cypher);                    
    } catch(Exception e) {     
      System.out.println("Exception: " + e);   
    } finally {
      if (f1 != null) {
         try {
           f1.flush();
           f1.close();
         } catch (Exception e) {}
      if (f != null) {
         try {
           f.close();
         } catch (Exception e) {}

  • Can't figure out where NullPointerException is coming from

    I will attach the code I have below. It is almost entirely done but i am getting a NullPointerException that is driving me nuts, and I can't figure out were it is coming from.
    Help is greatly appreciated.
    First code:
    import java.util.Scanner;
    import java.io.*;
    import java.util.Random;
    import java.util.Collection;
    public class DistributionPlagiarist
         public static void main(String[] args) throws IOException
              Scanner keyboard = new Scanner(System.in);
              int keyLength=0, phraseLength=0, numberOfPhrases=0;
              String inputFileName="", keepReadingFromFile="", theFile="";
              FrequencyLibrary text = new DenseFrequencyLibrary();
              if(args.length != 4)
                   System.out.println("The command line arguments you entered do not match what is needed.  Please try again.");
                   System.exit(0);
              for(int count=0; count<args.length; count++)
                   keyLength = Integer.parseInt(args[0]);
                   phraseLength = Integer.parseInt(args[1]);
                   numberOfPhrases = Integer.parseInt(args[2]);
                   inputFileName = args[3];
              if(keyLength < 0)
                   while(keyLength < 0)
                        System.out.print("The length of the key (" + keyLength + ")" + " you entered is less than zero.\nPlease enter another key length: ");
                        keyLength = keyboard.nextInt();
                        System.out.println();
              if(phraseLength < 0)
                   while(phraseLength < 0)
                        System.out.print("The desired length of the phrase (" + phraseLength + ")" + " you entered is less than zero.\nPlease enter another phrase length: ");
                        keyLength = keyboard.nextInt();
                        System.out.println();
              if(numberOfPhrases <= 0)
                   while(numberOfPhrases <= 0)
                        System.out.print("The desired number of phrases (" + keyLength + ")" + " you entered is not applicable.\nPlease choose another number: ");
                        keyLength = keyboard.nextInt();
                        System.out.println();
              File file=new File(inputFileName);
              boolean exists = file.exists();
              if (exists == false)
                   while(exists == false)
                        System.out.println("The file you are searching for does not exist.  Please place it in this programs directory.");
                        System.out.print("Please re-enter the file name: ");
                        inputFileName = keyboard.nextLine();
                        file=new File(inputFileName);
                        exists = file.exists();
              int count=keyLength, start=0, stop=0;
              FileReader freader = new FileReader(inputFileName);
              BufferedReader inputFile = new BufferedReader(freader);
              while(keepReadingFromFile != null)
                   keepReadingFromFile = inputFile.readLine();
                   if(keepReadingFromFile == null)
                        break;
                   else
                        theFile = theFile + keepReadingFromFile;
              while(count < theFile.length())
                   String name = theFile.substring(start, keyLength+stop);
                   char singleCharacter = theFile.charAt(count);
                   text.add(name, singleCharacter);
                   start++;
                   stop++;
                   count++;
              int countNumberOfPhrases=0;
              while(numberOfPhrases > 0)
                   countNumberOfPhrases++;
                   String phrase = randomphrase(text, phraseLength, keyLength);
                   System.out.println("Phrase " + countNumberOfPhrases + ":\n" + phrase);
                   numberOfPhrases--;
         private static String randomphrase(FrequencyLibrary textLibrary, int phraseLengthToMake, int startLength)
              String startString="";
              char characterToAdd=' ';
              startLength++;
              Random generator = new Random();
              int sizeOfLibrary=textLibrary.size()/2, randomInt = generator.nextInt(sizeOfLibrary+1), value=0;
              Collection<String> stringNames = textLibrary.makeStringCollection();
              for(String stringFromCollection : stringNames)
                   if(randomInt == value)
                        startString = stringFromCollection;
                   value++;
              String thePhrase = new String(startString);
              System.out.println("INITIAL START:" + startString + "TTTT");
              int substringStart=1;
              while(startLength < phraseLengthToMake)
                   characterToAdd = textLibrary.randomUniformChoose(startString);
                   thePhrase = thePhrase + characterToAdd;
                   System.out.println("CHARACTER:" + characterToAdd + "TTTT");
                   System.out.println("PHRASE:" + thePhrase + "TTTT");
                   startString = thePhrase.substring(substringStart, thePhrase.length());
                   boolean answer = textLibrary.contains(startString);
                   System.out.println(answer);
                   System.out.println("NEW STRING:" + startString + "TTTT");
                   startLength++;
                   substringStart++;
              return thePhrase;
    }Second code:
    import java.util.Collection;
    import java.util.HashMap;
    public class DenseFrequencyLibrary implements FrequencyLibrary
         private HashMap<String, MultiSetOfChar> bookTitleAndCharacterAndIntegerHashMap = new HashMap<String, MultiSetOfChar>();
         private MultiSetOfChar keyAndValuePairs = new DenseMultiSetOfChar();
          * Creates a new DenseFrequencyLibrary with all the essential things clear;
         DenseFrequencyLibrary()
              bookTitleAndCharacterAndIntegerHashMap.clear();
          * Input the value from the creation of the DensneMultiSetOfChar into a HashMap.  If the key
          * already exists then the value associated with it is updated by one.
          * @param character a char to be used in forming the HashMap
          * @return characterMap
         private HashMap<String, MultiSetOfChar> inputIntoMap(String name, char character)
              if(!bookTitleAndCharacterAndIntegerHashMap.containsKey(name))
                   keyAndValuePairs = new DenseMultiSetOfChar(character);
              else
                   keyAndValuePairs.add(character);
              this.bookTitleAndCharacterAndIntegerHashMap.put(name, keyAndValuePairs); //input character and value
              return bookTitleAndCharacterAndIntegerHashMap; //return the new HashMap
          * Returns the number of books in the library.
          * @return |b|, ie the number of books in b
        public int size()
             int numberOfBooks=bookTitleAndCharacterAndIntegerHashMap.size();
             return numberOfBooks;
         * Searches the library for an occurrence of a given book
         * @param target the name of a book to be searched for in the library
         * @return true if and only if the argument is already a book title in the library.
        public boolean contains(String target)
             boolean bookIsInLibrary=false;
             if(bookTitleAndCharacterAndIntegerHashMap.containsKey(target))
                  bookIsInLibrary = true;
             return bookIsInLibrary;
         * Returns the MultiSetOfChar that represents the occurrences of the individual characters
         * in the text of the book indicated by the argument.
         * @param target
         * @return MultiSetOfChar
        public MultiSetOfChar getFrequencies(String target)
             MultiSetOfChar frequencyMultiSetOfChar = bookTitleAndCharacterAndIntegerHashMap.get(target);
             return frequencyMultiSetOfChar;
         * Modifies the character occurrences associated with name to include one more occurrence of element.
         * @param name string of the name of the book
         * @param element character to add to the specified book
        public void add(String name, char element)
             bookTitleAndCharacterAndIntegerHashMap = inputIntoMap(name, element);
         * Modifies the character occurrences associated with name to include one less occurrence of element.
         * @param name string of the name of the book
         * @param element character to be removed from the specified book
         * @return true if and only if the book is modified.
        public boolean remove(String name, char element)
             boolean characterWasRemovedFromBook=false;
             //if the target character is in the map then remove it
              if(bookTitleAndCharacterAndIntegerHashMap.containsKey(name))
                   MultiSetOfChar keyAndValuePairs = bookTitleAndCharacterAndIntegerHashMap.get(name);
                   keyAndValuePairs.remove(element);
                   characterWasRemovedFromBook = true; //set answer to true because the HashMap was changed
              else //target does not exist in the HashMap
                   characterWasRemovedFromBook = false; //set answer to false because the HashMap was not changed
             return characterWasRemovedFromBook;
         * Returns a random character, chosen from the same distribution as the characters appear in the book.
         * For example, if 5% of the characters in "Alice in Wonderland" are an 'A', then this method should
         * return an 'A' about 5% of the time.
         * @param name string of the name of the book to search through and remove a character
         * @return true if and only if the argument is already a book title in the library.
         public char randomUniformChoose(String name)
            MultiSetOfChar keyAndValuePairs = bookTitleAndCharacterAndIntegerHashMap.get(name);
            char randomCharacter = keyAndValuePairs.randomUniformChoose();
              return randomCharacter; //return the random character pulled out
         public Collection<String> makeStringCollection()
              Collection<String> stringCollection = bookTitleAndCharacterAndIntegerHashMap.keySet();
              return stringCollection;
    }Third code:
    import java.util.HashMap;
    import java.util.Set;
    import java.util.Collection;
    import java.util.Random;
    * DenseMultiSetOfChar implements MultiSetOfChar.
    * @mathmodel b is a finite multiset
    * @mathdef
    *  |b| is the cardinality of b
    *  ||c,b|| is the number of occurrences of element c in b
    * @author Kyle Hiltner
    public class DenseMultiSetOfChar implements MultiSetOfChar
         private char characterInput=' ';
         private HashMap<Character, Integer> characterMap = new HashMap<Character, Integer>();
          * Create a new DenseMultiSetOfChar with zero argument
         DenseMultiSetOfChar()
              characterMap.clear(); //clear static HashMap
          * Create a new DenseMultiSetOfChar with the passed in value.
          * @param newChar character input to be added to the HashMap
         DenseMultiSetOfChar(char newChar)
              this.characterInput = newChar; //set characterInput to the value passed in
              characterMap = inputIntoMap(this.characterInput); //call private procedure to add characterInput to HashMap
          * Input the value from the creation of the DensneMultiSetOfChar into a HashMap.  If the key
          * already exists then the value associated with it is updated by one.
          * @param character a char to be used in forming the HashMap
          * @return characterMap
         private HashMap<Character, Integer> inputIntoMap(char character)
              //if the character is not in the HashMap then add it with the starting value of 1
              if(!characterMap.containsKey(character))
                   characterMap.put(character, 1); //input character and value
              else //character does exist
                   int value = characterMap.get(character); //get the value for the specified key
                   value++; //increase the value so as to show that another character was added
                   characterMap.put(character, value); //place the character and new value in the HashMap
              return characterMap; //return the new HashMap
          * Returns the number of elements in this multiset (ie its cardinality).
          * Note that since multisets can include duplicates, the cardinality may be
          * larger than the number of distinct elements. Also, the total number of
          * items in the multiset is bounded above by Integer.MAX_VALUE.
          * @return |b|, ie the cardinality of b
         public int getCardinality()
              int totalElementsInMap=0;
              Collection<Integer> integerCollection = characterMap.values(); //create a collection for easy iteration
              //iterate through each value in the HashMap and compute the total number of elements in the HashMap
              for(Integer valueFromCollection : integerCollection)
                   totalElementsInMap = totalElementsInMap + valueFromCollection; //compute new value of total values
              return totalElementsInMap; //return the final total value
          * Returns the number of occurrences of a given element in the multiset. A
          * simple identity relating getElementCount and getCardinality is that the
          * sum of getElementCount for each char is equal to the cardinality of the
          * set.
          * @param target
          *            char to be counted in the multiset
          * @return ||target,b||, ie the number of occurrences of target in b
         public int getElementCount(char target)
              int numberOfGivenCharacters=0; //set initial value
              //if the HashMap contains the target character then numberOfGivenCharacters is set to the value
              if(characterMap.containsKey(target))
                   numberOfGivenCharacters = characterMap.get(target); //set numberOfGivenCharacters to the value assigned to the target character
              return numberOfGivenCharacters; //return the value for the target character
          * Returns a set such that every element in the multiset is in the set (but
          * no duplicates). The cardinality of the returned set must be less than or
          * equal to |b|. The cardinality of the two are equal if and only if b
          * contains no duplicate elements.
          * @return a set of Character, s, such that: <br />
          *         (for all (Character)i in s : (char)i in b) and <br />
          *         (for all (char)i in b : (Character)i in s)
         public Set<Character> getElementSet()
              Set<Character> characterSet = characterMap.keySet(); //create a Set from the keys of characters in the HashMap     
              return characterSet; //return the character Set
          * Adds a single element to the multiset. This operation always increases
          * the cardinality of the multiset by 1, assuming that the maximum capacity
          * of Integer.MAX_VALUE has not been reached.
          * @param item
          *            the char to be added to b
          * @requires |b| < Integer.MAX_VALUE
          * @alters b
          * @ensures b = #b union {item}
         public void add(char item)
              characterMap = inputIntoMap(item); //call the private method to add new character (item) to the HashMap
          * Removes the target, if it is present in the multiset. The method returns
          * true if and only if it changes the multiset.
          * @param target
          *            the char to be removed
          * @alters b
          * @ensures (target not in #b) ==> (b = #b) <br />
          *          (target in #b) ==> (b union {target} = #b)
          * @return target in #b
         public boolean remove(char target)
              boolean answer=false; //set initial value to false
              //if the target character is in the map then remove it
              if(characterMap.containsKey(target))
                   int value = characterMap.get(target); //find the value associated with the target character
                   //if the value is 1 call remove from the HashMap and remove key and value
                   if(value == 1)
                        characterMap.remove(target); //remove key and value from the HashMap
                   else //value is greater than 1
                        value--; //decrease value to show removal
                        characterMap.put(target, value); //replace target character with new value back into the HashMap
                   answer = true; //set answer to true because the HashMap was changed
              else //target does not exist in the HashMap
                   answer = false; //set answer to false because the HashMap was not changed
              return answer; //return answer
          * Returns a char chosen randomly based on the contents of the multiset.
          * This operation does not remove the char from the multiset or change the
          * multiset in any way. In particular, the cardinality of the multiset is
          * the same before and after this method.
          * <p>
          * Characters should be returned with a random distribution equal to the
          * distribution of characters in the multiset. That is, for a character that
          * appears N times in a multiset of cardinality M, the probability of that
          * character being returned is N / M. For example, a multiset that contains
          * only the character 'a', possibly many times, would always result in an
          * 'a' being generated. On the other hand, a multiset with an equal number
          * of 'a' and 'b' elements would return an 'a' approximately half the time
          * and a 'b' the other half.
          * @requires |b| >= 1
          * @return char c with probability p, where: <br />
          *         p = ||c,b|| / |b|
         public char randomUniformChoose()
              char randomCharacter=' ';
              Random generator = new Random();
              int totalElementsInMap=0;
              Collection<Integer> integerCollection = characterMap.values(); //create a collection for easy iteration
              //iterate through each value in the HashMap and compute the total number of elements in the HashMap. 
              //Do this in case a remove call was made
              for(Integer valueFromCollection : integerCollection)
                   totalElementsInMap = totalElementsInMap + valueFromCollection; //compute new value of total values
              int randomInt = generator.nextInt(totalElementsInMap+1), lowerValue=0, upperValue=0;
              Collection<Character> keyCollection = characterMap.keySet();
              //iterate through each value in the HashMap and compute the total number of elements in the HashMap
              for(Character keyFromCollection : keyCollection)
                 upperValue = upperValue + characterMap.get(keyFromCollection);
                 if(randomInt == upperValue)
                      randomCharacter = keyFromCollection;
                 if(randomInt >= lowerValue && randomInt <= upperValue)
                      randomCharacter = keyFromCollection;
                 lowerValue = upperValue + 1;
              return randomCharacter; //return the random character pulled out
    }The Error:
    Exception in thread "main" java.lang.NullPointerException
         at DenseFrequencyLibrary.randomUniformChoose(DenseFrequencyLibrary.java:137)
         at DistributionPlagiarist.randomphrase(DistributionPlagiarist.java:146)
         at DistributionPlagiarist.main(DistributionPlagiarist.java:112)I will attempt to explain what this does in as few words as possible. For a breakdown of the lab go urlhttp://www.cse.ohio-state.edu/~paolo/teaching/494MJ/labs/lab8.shtml{url}. If you don't feel like reading that: THe program reads in some command line arguments. From there it reads from the file provided in the command line and creates "keys" from the specified length. From there I need to create a phrase of the specified length. If i am supposed to create more then one then i do. That is pretty much it. I can't figure out where (really why) the NullPointerException error is coming from.
    Help is appreciated!!

    Post the actual error text (copy and paste, don't "interpret" it) here.
    It should include a stack trace which references a line number of the program -
    unless you suppressed the trace, in which case change your error handling
    so that the trace is produced.
    Identify which program line in your post the error is pointing to so that we can match
    the error with your program, since your post doesn't have line numbers..
    Edited by: ChuckBing on Nov 16, 2007 7:19 PM
    Also - posting large amounts of code (as you did) will reduce the chance of anyone helping

  • Upload xml file from aplication server using read dataset, parser error.

    Hi,
    I would like to upload xml file from app. server but parser failed. If I upload this xml file from workstation (using ws_upload) it is correct. For uploading xml file from app. server I use open dataset... read dataset. In loop section I remove '#' char. How do You upload xml file from app server? What Could be incorrect.
    I try to open dataset in binary mode, text mode...
    TYPES: BEGIN OF xml_line,
            data(255) TYPE c,
          END OF xml_line.
    DATA: gt_xml_table TYPE TABLE OF xml_line,
          gs_xml_structure TYPE  xml_line,
          gv_xml_table_size TYPE i.
    OPEN DATASET s FOR INPUT IN BINARY MODE.
      IF sy-subrc <> 0.
        MESSAGE e001(zet) WITH '....'.
      ENDIF.
      DO.
        READ DATASET s INTO gs_xml_structure.
        IF sy-subrc <> 0.
          EXIT.
        ELSE.
         len = STRLEN( gs_xml_structure ).
         len = len - 1.
         check len > 0.
         WRITE gs_xml_structure(len) TO gs_xml_structure.
          APPEND gs_xml_structure TO gt_xml_table.
        ENDIF.
      ENDDO.

    You Can do this too
    parameters: p_file like rlgrap-filename.
    data: subrc like sy-subrc.
      create object me.
      REFRESH t_data.
    *  Open XML File
      CALL METHOD me->CREATE_WITH_FILE
        EXPORTING
          filename = p_file
        RECEIVING
          retcode  = subrc.
    * Saves Data in an itab from XML File.
      CALL METHOD me->get_data
        IMPORTING
          retcode    = subrc
        CHANGING
          dataobject = t_data[].
    Regards,
    Claudio.

  • File XML Content Conversion: Problem with special characters

    Hello,
    in a file sender cc content conversion is used to transform a flat structure to XML. What we experiencecd is that the message mapping failed due to a character that was not allowed in XML:
    I was assuming that the file content conversion just creates XML messages with allowed characters. Is there any way to configure content conversion to remove control characters which are not allowed in XML? Unfortunately the sender system cannot be modified.
    Thank you.

    Hi Florian,
      Please use this UDF to remove special characters which prevent XML messages to form properly.
    public static String removeSpecialChar(String s)
              try
                   s=s.replaceAll("&","& amp ;");
                   s=s.replaceAll("<"  , "  & lt ;");
                   s=s.replaceAll(">", "& gt ;");
                   s=s.replaceAll("'", "& apos ;");
                   s=s.replaceAll("\"", "& quot ;");
              catch(Exception e)
                   e.printStackTrace();
              return s;
    Please remove spaces between characters within double quotes. I have added them because otherwise you can't see this code properly. Please check this below link , please replace the characters with proper values as the display is causing a problem here   
    http://support.microsoft.com/kb/316063
    regards
    Anupam
    Edited by: anupamsap on Jul 7, 2011 4:22 PM
    Edited by: anupamsap on Jul 7, 2011 4:23 PM

Maybe you are looking for

  • Reg : Creation of Transparent table in background

    Hi Experts,    Whether is it advisable to use 'CL_REBF_DDIC_TABL'  to create a transparent table.     I have used PUT_COMPLETE in this class to create the table, I am able to create it.     This method has a import parameter 'ID_MSGLIST', I am not ge

  • Unable to upload RTF file in the long text

    Hi all, Could you please help me out in this issue. I am trying to upload the RTF file in the long text editor through this menu path Text-> Upload->RTF file.The RTF file is about only 56 KB memory size consists only texts. I could able to select the

  • How to set value of textinputbean in am

    hi guys,I have an item on my oaf page that is non data base item and i want to set its value in AM.Actually I am calling a DB procedure in AM that return me a value now i want to set this value in TextinputBean.but i dont know how to set a non databa

  • 2G Touch - Looking for a dock, video out, synch, ac charge?

    Is there a dock that does all of these things? I know I saw some from belkin but their descriptions weren't that good. This one: http://catalog.belkin.com/IWCatProductPage.process?Product_Id=370997 says it charges AC and does video out, but does anyo

  • Vector - From Photoshop to Illustrator ***CAN IT BE DONE?****

    I'm sure this is basic for you guys, But I have a situation here...I made a  design in Ps ( 3" x 4" label at 300dpi) its very simple; one font, one logo and a QR code. Every layer was converted into a custom shape and all merged into one vector layer