CharAT Throws StringIndexOutOfBoundsException.

The program works fine until the user has finished entering the Swell Heights then it returns to the menu and then Throws this silly exception.
=(
import java.util.Scanner; //import the Scanner Class
import java.lang.reflect.Array; //import the Array Class
@Program Name: SwellHeights.java
@Purpose: To get swell information and the display
           proccessed information about the swells.
//Start of the Program
public class SwellHeights
  //creates a Global Array so that the functions can get access to it
  public static float[] arraySwellHeight = new float[7];
  //Start of the MAIN function
  public static void main(String args[])
    float day = 0; //Init var to get data from dayLargeSwell()
    float smallest = 0; //Init var to get data from smallSwell()
    float largest = 0; //Init var to get data from largeSwell()
    float average = 0; //Init var to get data from averageSwell()
    Scanner in = new Scanner (System.in); //Creates a scanner to capture input   
    char choice; //declare var for use in Case Statement
    do //Starts do while loop
       //Program heading
       System.out.println("SWELL HEIGHT ANALYSIS PROGRAM");
       System.out.println("*****************************");
       System.out.println("");
       System.out.println("a)    Enter maximum daily swell heights");
       System.out.println("b)    Analyse swell height figures");
       System.out.println("c)    Exit program");
       System.out.println("");
       System.out.println("Enter Option a, b or c");
       System.out.println("Please use lowercase for your answer.");
       System.out.println("");
       String s = in.nextLine(); //Sets user input as s
       choice = s.charAt(0); //charAt only reads the 1st char in s
       //Switch statment to define where the program will go to
       switch(choice)
           //If a in input form user it runs this section
           case 'a' :
                 int count; //declares a counter to use in for loop
                 System.out.println("");
                 System.out.println("ENTER MAXIMUM SWELL HEIGHTS FOR THE LAST 7 DAYS");
                 System.out.println("===============================================");
                 System.out.println("Note: Input swell height figures in metres");
                 System.out.println("");
                 System.out.println("Enter 7 daily Swell Hieghts\n");
                 for (count = 0; count < 7; count++)
                 //This loop will run 7 times
                      System.out.print(" Enter swell heights for day " + (count+1)+" $: ");
                      SwellHeights.arraySwellHeight [count] = in.nextFloat();
                      System.out.println(SwellHeights.arraySwellHeight [count]);
                      //This is creating an Array with 7 elements
                System.out.println("");
                //Stops the program from carrying on to case b
                break;
           //If b is input from user it runs this section
           case 'b' :
                System.out.println("");
                System.out.println("MAXIMUN DAILY SWELL HEIGHTS FOR THE WEEK"); 
                System.out.println("****************************************");
                System.out.println("");
                System.out.println("   Day  Metres");
                System.out.println("   ---  ------");
                // + SwellHeights.arraySwellHeight[#] displays what is inside that element
                System.out.println("     1  " + SwellHeights.arraySwellHeight[0]);
                System.out.println("     2  " + SwellHeights.arraySwellHeight[1]);
                System.out.println("     3  " + SwellHeights.arraySwellHeight[2]);
                System.out.println("     4  " + SwellHeights.arraySwellHeight[3]);
                System.out.println("     5  " + SwellHeights.arraySwellHeight[4]);
                System.out.println("     6  " + SwellHeights.arraySwellHeight[5]);
                System.out.println("     7  " + SwellHeights.arraySwellHeight[6]);
                System.out.println("");
                System.out.println("============================================================================");
                System.out.print("Average swell height    : " );
                average = averageSwell(); //calls the averageSwell() function
                System.out.println(average); //prints out the result of that functions process
                System.out.print("Smallest swell height   : " );
                smallest = smallSwell(); //calles the  smallSwell() function
                System.out.println(smallest); //prints out the result of that funtions process
                System.out.print("Largest swell height    : " );
                largest = largeSwell(); //calles the largeSwell() function
                System.out.print(largest); //prints out the result of the functions process
                System.out.print(" metres occured on day ");
                day = dayLargeSwell(); //calles the daylargeSwell() function
                System.out.println(day); //prints out the result of that functions process
                System.out.println("============================================================================");
                System.out.println("");
                //Stops the program from carrying on to case c
                break;
           //If c in input form user it runs this section  
           case 'c' :
                System.out.println("");
                System.out.println("Thank you and Goodbye");
                //Stops the program from carrying on to default
                break;
           default :
                System.out.println(choice+ " Is An Invalid Selection" );
                System.out.println("");
                //Stops the program from exiting the case statement
                break;
          //End of Case Statement
    //End of Do-While Loop, when user enters c
    while(choice != 'c');
  //End of main()
  Purpose: To calculate the average swell
           height from the values in the
           Array.
  @return: Returns the average to be
           displayed in main()   
  public static float averageSwell()
    int count = 0; //Init var for Do-While Loop
    float total = 0.0f; //Init var for the total
    float average = 0.0f; //Init var to hold the average
    //Start of Do-While loop
    do
      //Accumulate Total
       total = total + SwellHeights.arraySwellHeight[count];
       count = count + 1;
    //Finishes when count is equal to 7
    while (count < 7);
    //Average is total / number of elements
    average = total/count;
    //Returns the average var to main()
    return average;
   }//end of averageSwell()
  Purpose: To calculate the minimum swell
           height from the values in the
           Array.
  @return: Returns the minimum to be
           displayed in main()   
  public static float smallSwell()
    int count = 0; //Init var for Do-While Loop
    float minimum; // Declare float to hold minimum
    //minimum is then assigned the first element
    minimum = SwellHeights.arraySwellHeight[0];
    //Start of Do-While loop
    do
      //Check for new minimum
       if (SwellHeights.arraySwellHeight[count] < minimum)
         //New minimum
         minimum = SwellHeights.arraySwellHeight[count];
      //Incrementing count
      count = count + 1;
    //Finishes when count is equal to 7
    while (count < 7);
    //Returns the minimum var to main()
    return minimum;
   } //End of smallSwell()
  Purpose: To calculate the maximum swell
           height from the values in the
           Array.
  @return: Returns the maximum to be
           displayed in main()   
  public static float largeSwell()
    int count = 0; //Init var for Do-While Loop
    float maximum; // Declare float to hold maximum
    //maximum is then assigned the first element
    maximum = SwellHeights.arraySwellHeight[0];
    //Start of Do-While loop
    do
      //Check for new maximum
       if (SwellHeights.arraySwellHeight[count] > maximum)
        //New maximum
        maximum = SwellHeights.arraySwellHeight[count];
       //Incrementing count
       count = count + 1;
    //Finishes when count is equal to 7
    while (count < 7);
    //Returns the maximum var to main()
    return maximum;  
   } //End of largeSwell()
  Purpose: To calculate the day of the
           largest swell height from the
           values in the Array.
  @return: Returns the day of the largest
           swell to be displayed in main()   
  public static float dayLargeSwell()
    int count = 0; //Init var for Do-While Loop
    int day = 0; //Init var to hold days
    float maximum; //Declare float to hold maximum
    //maximum is then assigned the first element
    maximum = SwellHeights.arraySwellHeight[0];
    //Start of Do-While loop
    do
       //Check for new maximum
       if (SwellHeights.arraySwellHeight[count] > maximum)
        //New maximum
        maximum = SwellHeights.arraySwellHeight[count];
        //Maximum element number caputured
        day = count + 1;
       //Incrementing count
       count = count + 1;
    //Finishes when count is equal to 7
    while (count < 7);
    //Returns the day var to main()
    return day;  
  } //End of dayLargeSwell
} //End of Program

charAt throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string.
A quick look at your code shows that you are using charAt only once:String s = in.nextLine(); //Sets user input as s
choice = s.charAt(0); //charAt only reads the 1st char in sThe conclusion is that s has a length of zero.
I guess this could happen when user hits the return key without entering a character (or might come from Scanner behaviour when using nextFloat() followed by nextLine(), I don't know much about Scanner as I'm still stuck to 1.4 .)
You could therefore add a check on user input before trying to extract the character, something like:String s = null;
while((s = in.nextLine()).length() < 1); //read user input until it is not empty
choice = s.charAt(0); //charAt only reads the 1st char in sHope it helps.

Similar Messages

  • JDM throws StringIndexOutOfBoundsException

    Hi all,
    While migrating some modules from Designer ,JDM is throwing:
    StringIndexOutOfBoundsException: String index out of range: -6
    at java.lang.String.substring(String.java:1768)
    at racle.jheadstart.dt.jmig.CustomPropertiesMigrator.retrieveMultiLineText(CustomPropertiesMigrator.java:108)
    at oracle.jheadstart.dt.jmig.EOCustomPropertiesMigrator.processElement(EOCustomPropertiesMigrator.java:394)
    at oracle.jmig.paths.AbstractMigrator.migrate(AbstractMigrator.java:110)
    at oracle.jmig.MigrationPathWalker.callMigrators(MigrationPathWalker.java:271)
    at oracle.jmig.MigrationPathWalker.migrateTo(MigrationPathWalker.java:196)
    at oracle.jmig.MigrationPathWalker.migrateTo(MigrationPathWalker.java:219)
    at oracle.jmig.MigrationPathWalker.migrateTo(MigrationPathWalker.java:219)
    at oracle.jmig.MigrationPathWalker.migrateTo(MigrationPathWalker.java:219)
    at oracle.jmig.MigrationPathWalker.migrate(MigrationPathWalker.java:147)
    at oracle.jmig.MigrationRunnable.migrate(MigrationRunnable.java:363)
    at oracle.jmig.MigrationRunnable.migrate(MigrationRunnable.java:213)
    at oracle.jmig.MigrationRunnable.run(MigrationRunnable.java:122)
    at oracle.ide.dialogs.ProgressBar.run(ProgressBar.java:551)
    at java.lang.Thread.run(Thread.java:595)
    Oddly enough, the value of the index is always -6. Anyone encountered this kind of error?
    Many thanks!
    Boris

    No, we didn't receive a testcase, so it is hard to fix.
    Note that we are currently building the JHeadstart Forms Migrator, which directly converts Forms .fmb files to ADF. Most customers don't use Designer at all to generate forms, or modfied the forms after generation, so by directly reading the forms .fmb files, we can produce better migration results for a much larger customer base.
    With the JFM, it will also be easier to provide support, since we only need the extracted XML file that is created as the first step in the migration process to reproduce migration errors.
    We plan to release a first version of the JFM as part of the JHeadstart 10.1.3.3 release, currently scheduled for the may/june timeframe.
    Steven Davelaar,
    JHeadstart team.

  • Introspector.getBeanInfo throws StringIndexOutOfBoundsException

    Hi all, the following code throws a
    "java.lang.StringIndexOutOfBoundsException: String index out of range: -3" error.
    OtherClass myclass = null;
    Class klas = Class.forName(myClassName);
    myclass = (OtherClass) klas.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(myclass.getClass());
    -- error after this line!!!
    Can anyone tell me what is going on here? THANKS!!!

    I believe I found the "answer" to this problem.
    Please see the bug report at http://developer.java.sun.com/developer/bugParade/bugs/4523072.html

  • CharAt and StringIndexOutOfBoundsException ???

    Hey all
    I'm trying to parse this file, and in order to do it I need to read every character in the file. To do this i read the text file line by line then I do this
              while ((line = bdr.readLine()) != null) {
                        for (int k = 0; k < line.length(); k++) {
                             String character = new String();
                             String character2 = new String();
                             String character3 = new String();
                             String character4 = new String();
                             character = "" + line.charAt(k);
                             System.out.println("Character:" + character);
                             //CHAPTER / VERSE CHECK
                             if(isNumber(character)) {
                                     if(line.charAt(k + 1) != -1) {
                                       System.out.println("Number1:" + character);                                
                                            character2 = "" + line.charAt(k+1);
                                              if (checkPeriod(character2)) {
                                             System.out.println("Period:" + character2);
                                            if (line.charAt(k + 2) != -1) {
                                                 character3 = "" + line.charAt(k + 2);
                                                 System.out.println("Number2:" + character3);
                                  //REB CHECK
                                  if (character.equals("R")) {
                                       character2 =  "" + line.charAt(k + 1);
                                       if(character2.equals("E")) {
                                            character3 = "" + line.charAt(k + 2);
                                            if(character3.equals("B")) {
                                                 bookName = ""+line.charAt(k + 4) + line.charAt(k + 5) + line.charAt(k + 6);
                                                 System.out.println("Book Name:" + bookName);
              }The error seems to happen here
    if(line.charAt(k + 1) != -1)
    how can I get the next character without having this error?
    java.lang.StringIndexOutOfBoundsException: String index out of range: 15
         at java.lang.String.charAt(Unknown Source)
         at translator.ReadFile.<init>(ReadFile.java:49)
         at translator.Main.main(Main.java:58)
    Exception in thread "main"

    You iterate k from 0 to line.length():
    for (int k = 0; k < line.length(); k++) {
    and then ask about char at line.length() + 1 position:
    line.charAt(k + 1)
    Just iterate to line.length() - 1.

  • Throwing index out of bound exception- please explain to fix the error

    import java.util.StringTokenizer;
    import java.lang.String;
    public class tokenize
              String s="I have learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel. ";
              String s1="Nature always wears the colors of the spirit.";
                        public void noofwords()
                             StringTokenizer str= new StringTokenizer(s," ");
    StringTokenizer str1= new StringTokenizer(s1," ");
                             System.out.println("the no of words in the string s is: "+str.countTokens()+" and the number of words in s1 is: "+str1.countTokens);
                        public void nooflines()
                             StringTokenizer str2= new StringTokenizer(s1,".,?");
                             StringTokenizer str3 = new StringTokenizer(s,".,?");
                             System.out.println("the number of lines in string s is: "+str3.countTokens()+" "+"and number of lines in the string s1 is: "+str2.countTokens());
                        public void noofchars()
                             System.out.println("no of characters in string s is: "+s.length()+ " " +"and the number of lines in the string s1 is : "+s1.length());
                        public void noofvowels()
                             StringTokenizer str4 = new StringTokenizer(s," ");
                             String strpackets;
                             int count =0;
                             if(str4.hasMoreElements())
                                  strpackets= str4.nextToken();
                                  for( int a=0;a<=strpackets.length();a++)
                                       char c= strpackets.charAt(a);
                                            if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
                                                 count++;
                             System.out.println("the number of vowels in the sring s is: "+count);
         public static void main(String[] args)throws StringIndexOutOfBoundsException
              tokenize tze = new tokenize();
              tze.noofwords();
              tze.noofchars();
              tze.nooflines();
              tze.noofvowels();
    Edited by: 881507 on Sep 10, 2012 9:46 PM

    Provide the exception stacktrace.
    Post your code inside the code tag.
    881507 wrote:
    public class tokenize Follow the convention to writing a class.
    public class Tokenize 881507 wrote:System.out.println("the no of words in the string s is: "str.countTokens()" and the number of words in s1 is: "+str1.countTokens);is this compiled?
    881507 wrote:
    char c= strpackets.charAt(a);this is the point which throw the exception.
    It should be
    for( int a=0;a<strpackets.length();a++)

  • I get confuse WHY the createImage cant run well or get nullpointer error??

    Try to help me..why my createImage in Ticker.class can run BUT when I decide to move to TickerTape.class then it come out the error which at below:
    java.lang.NullPointerException
         at TickerTape.initImage(TickerTape.java:87)
         at Ticker.update(Ticker.java:511)
         at Ticker.paint(Ticker.java:488)
         at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
         at sun.awt.RepaintArea.paint(RepaintArea.java:224)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
         at java.awt.Component.dispatchEventImpl(Component.java:4031)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    java.lang.NullPointerException
         at TickerTape.initImage(TickerTape.java:87)[Ticker Ver 4.0] :1. Running LATEST version!!!
    [Ticker Ver 4.0] :2. 25 JULY 2008,5:14:38PM!!!
         at Ticker.update(Ticker.java:511)
         at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
         at sun.awt.RepaintArea.paint(RepaintArea.java:216)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
         at java.awt.Component.dispatchEventImpl(Component.java:4031)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    java.lang.NullPointerException
         at TickerTape.initImage(TickerTape.java:87)
         at Ticker.update(Ticker.java:511)
         at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
         at sun.awt.RepaintArea.paint(RepaintArea.java:216)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
         at java.awt.Component.dispatchEventImpl(Component.java:4031)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)If Socket is not null..
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    <applet code=Ticker.class width=300
    height=28>
    <param name=count value=2>
    <param name=msg0 value= "Welcome to Fred Fargle's Homepage.. Just Click to Connect *** \\No Link">
    <param name=msg1 value="Visit:  ALCo -- Access LaPorte County  \\http://www.alco.org/">
    <param name=increment value=8>
    <param name=bgco value=50,0,200>
    <param name=txtco value=250,250,0>
    <param name=linkco value=180,25,21>
    </applet>
    import java.applet.Applet;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Event;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectOutputStream;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.UnknownHostException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.StringTokenizer;
    import java.util.Vector;
    public class Ticker extends Applet implements Runnable
    //     public static final String FIRST_LINE_DATA = "1^Consumer Products^327.77^+0.41^2^Industrial Products^105.39^+3.26^3^Construction^234.99^+16.22^4^Trading Services^174.56^+13.54^5^Technology^19.35^+0.04^10^Finance^10001.49^+743.35^20^Property^754.87^+0.16^25^Plantation^7810.60^-1.04^30^Mining^362.73^+0.00^200^Composite^1317.93^+88.58^300^Industrial^2875.13^+270.04^";
    //     public static final String LINE_DATA = "1^322.34^-1.75^2^99.15^-1.47^3^209.82^-5.15^4^155.89^-2.33^5^18.54^-0.29^10^8821.04^-181.79^20^722.83^-17.05^25^7921.79^-75.81^30^358.68^-2.03^200^1196.39^-16.20^300^2560.89^-21.24^861^7739.76^-112.61^862^7731.92^-104.72^863^7644.76^-140.11^864^9791.39^-168.25^865^7970.97^-118.60^866^7045.63^-149.98^867^8762.71^-110.11^868^8704.34^-102.22^869^9880.95^-105.10^870^5517.77^-78.36^871^4367.08^-145.64^";
         public static boolean DATA_FETCHED = false;
         private static final long serialVersionUID = -3405790462792767823L;
         public static boolean LOADING_DATA = false;
         TickerTape tickerTape = new TickerTape();
         public int messageIndex;
         public int messageCount;
         public boolean bStop=false;
         public String message;
         public Font messageF;
         public int messageX;
         public int messageY;
    //     public int messageW;
         public String url_;
         int increment = 1;
         public Thread t;
         public boolean active;
         public boolean flag = true;
         public Color txtCo;
         public Color linkCo;
         public Color bgCo;
         public Dimension lastS;
         public String sFirst;
         public int iIdx;
         Image image;
         //Graphics gr;
         public long milliSeconds = 100;
         boolean display_URL;
         int mouseX;
         // mouseY;
         int itemIndex = 0;
         Vector<DisplayItem> diVector = null;
         DisplayItem dispItem = null;
         FontMetrics fontmetrics1 = null;
         public static int MOUSE_NONE = 0;
         public static int MOUSE_CLICK = 1;
         public static int MOUSE_MOVE = 2;
         public static long MILLIS = 2;
        long scrollSpeed = tickerTape.getScrollSpeed();
         String appletParameters[][];
         Button btnScrollControl;
         String fontName = DisplayItem.DEFAULT_FONT_NAME;
         int fontStyle = DisplayItem.DEFAULT_STYLE;
         int fontSize = DisplayItem.DEFAULT_SIZE;
         Color textColor = DisplayItem.DEFAULT_TEXT_COLOR;
         int scrollDirection, mouseEvent = MOUSE_MOVE;
         String sData ="";
         String vendor = "";
         String Version = "Ticker Ver 4.0";
         String SessionID = "";
         String sHeader = "";
         int bRead;
         private String SendStr = "";
         Socket socket=null;
         DataInputStream input=null;
         PrintStream output;
         String feed;
         String host;
         String sTmp;
         String UserRef = "";
         String UserID;
         String BrokerID = "MYETRADE";
         Thread myThread;
         boolean bLoopThread = false;
         int intSleepTimer = 15;
         String SleepTimer = "";
         int sleepLoop = 0;
         boolean isSocket = true;
         boolean bSelfKill = false;
         boolean Timeout = false;
         private int TimeoutType = 0;
         long delay = MILLIS;
          boolean running = true;
         // int p = 0;
         // int j = 0;
         // int startPost = 0;
         // int LastPost = 0;
          int ItemToDisplay = 0;
         // int stringWidth = 0;
         // int x;
         // int y;
          private static boolean FIRST_LINE = true;
         SimpleDateFormat formattime = new SimpleDateFormat("HH:mm:ss ");
         Thread timeThread;
         Calendar calendar;
         //Dimension d;
         class heartBeatThread extends Thread
              int iTimerCount = 0;
              int iTimeoutCount = 15;
              public void setTimeoutNow()
                   iTimerCount = iTimeoutCount + 1;
              public void setTimeout(int iValue)
                   iTimeoutCount = iValue;
              public boolean getTimeout()
                   boolean bTimeout = false;
                   if (iTimerCount > iTimeoutCount)
                        bTimeout = true;
                   return bTimeout;
              public void resetTimer()
                   iTimerCount = 0;
              public void run()
                   while (true)
                        try
                             Thread.sleep(6000);
                             calendar = Calendar.getInstance();
                             if (iTimerCount > iTimeoutCount)
                                  iTimerCount = iTimeoutCount + 1;
                             else
                                  iTimerCount++;
                        } catch (Exception e)
         heartBeatThread HBT = null;
         public void timeoutNow()
              HBT.setTimeoutNow();
              Timeout = true;
              TimeoutType = 1;
         @SuppressWarnings("deprecation")
         public void init()
         //      d = getSize();
           //      image = createImage(d.getSize().width, d.getSize().height);
                 //      tickerTape.TickerTape(image);
               host = getCodeBase().getHost();
               this.appletParameters = getParameterInfo();
              if (this.appletParameters != null)
                   int noOfParamaters = this.appletParameters.length;
                   for (int i = 0; i < noOfParamaters; i++)
                        if (this.appletParameters[0].equals("font"))
                             this.fontName = this.appletParameters[i][1];
                        else if (this.appletParameters[i][0].equals("style"))
                             if (this.appletParameters[i][1].equals("plain"))
                                  this.fontStyle = Font.PLAIN;
                             else if (this.appletParameters[i][1].equals("bold"))
                                  this.fontStyle = Font.BOLD;
                             else if (this.appletParameters[i][1].equals("italic"))
                                  this.fontStyle = Font.ITALIC;
                             else if(this.appletParameters[i][1].equals("underline"))
                                  this.fontStyle = Font.ROMAN_BASELINE; // need to verify
                        else if (this.appletParameters[i][0].equals("size"))
                             this.fontSize = Integer.parseInt(this.appletParameters[i][1]);
                        else if (this.appletParameters[i][0].equals("color"))
    //                         this.textColor = this.appletParameters[i][1];
                        else if (this.appletParameters[i][0].equals("scroll_start"))
                             if (this.appletParameters[i][1].equals("left"))
                                  this.scrollDirection = TickerTape.SCROLL_LEFT;
                             else if (this.appletParameters[i][1].equals("right"))
                                  this.scrollDirection = TickerTape.SCROLL_RIGHT;
                             else if (this.appletParameters[i][1].equals("top"))
                                  this.scrollDirection = TickerTape.SCROLL_DOWN;
                             else if (this.appletParameters[i][1].equals("bottom"))
                                  this.scrollDirection = TickerTape.SCROLL_UP;
                        else if (this.appletParameters[i][0].equals("event"))
                             if (this.appletParameters[i][1].equals("move"))
                                  this.mouseEvent = MOUSE_MOVE;
                             else if (this.appletParameters[i][1].equals("click"))
                                  this.mouseEvent = MOUSE_CLICK;
                        else if (this.appletParameters[i][0].equals("delay"))
                             this.delay = Integer.parseInt(this.appletParameters[i][1]);
              //setSize(tickerTape.cParamsHeight(),tickerTape.cParamsWidth());
              //int x=900;
              //int y=40;
              tickerTape.setSize(900,40);
              setSize(900,40);
              //setSize(tickerTape.setWidthSize(900),tickerTape.setHeightSize(40));
              //setSize(900, 40);
              if(this.textColor == null)
                   tickerTape.setTickerDefaultColor(Color.WHITE);
              else
                   tickerTape.setTickerDefaultColor(this.textColor);
              tickerTape.setBgColor(Color.BLACK);
              // get Font Properties
              // If they are null create a new default font.
              if(this.fontName == null)
                   //tickerTape.setTickerDefaultFont(new Font("Times New Roman", Font.PLAIN, 12));
                   tickerTape.setTickerDefaultFont(new Font("Arial", Font.PLAIN, 13));
              else
                   //this.fontName = "Verdana";this.fontStyle = Font.BOLD;this.fontSize = 14;
                   this.fontName = "Arial";this.fontStyle = Font.BOLD;this.fontSize = 13;
                   tickerTape.setTickerDefaultFont(new Font(this.fontName, this.fontStyle, this.fontSize));
              this.scrollDirection = TickerTape.SCROLL_RIGHT;
              tickerTape.setScrollDirection(this.scrollDirection);
              setDelay(this.delay);
              tickerTape.setBgColor(0,0, 0);
              this.setLayout(null);
              this.btnScrollControl = new Button("Pause");
              this.btnScrollControl.setActionCommand("Pause");
              this.btnScrollControl.setBounds(this.getWidth() - 50, 0, 50, 35);
              this.btnScrollControl.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
                        Button btn = ((Button) evt.getSource());
                        String cmd = btn.getActionCommand();
                        if (cmd.equals("Pause"))
                             try
                                  t.suspend();
                             } catch (Exception e)
                                  e.printStackTrace();
                             btn.setActionCommand("Scroll");
                             btn.setLabel("Scroll");
                        else if (cmd.equals("Scroll"))
                             try
                                  t.resume();
                             } catch (Exception e)
                                  e.printStackTrace();
                             btn.setActionCommand("Pause");
                             btn.setLabel("Pause");
    //          this.add(this.btnScrollControl);
         public void createParams()
         {//tickerTape.x = 900;
              //tickerTape.y = 40;
              int width = getSize().width;
              //System.out.println("getSize().width "+getSize().width);
              int height = getSize().height;
              lastS.width = width;
              lastS.height = height;
              System.out.println("width"+width);
              //System.out.println("width: " + width + " height: " + height);
              tickerTape.createParamsgr();
              if (image != null)
                   image = null;
              Font font = tickerTape.getDefaultFont();
              this.setFont(font);
              FontMetrics metrics = getFontMetrics(font);
              metrics = getFontMetrics(font);
              int k = getFontMetrics(font).getHeight();
              //tickerTape.cParams();
              //tickerTape.createParams1(lastS);
              //setSize(tickerTape.cParamsHeight(),tickerTape.cParamsWidth());
         //     messageY = tickerTape.cParamsY();
              messageX = width;
              messageY = (height - k >> 1) + metrics.getAscent();
                   int sWidth = getSize().width;
                   int sHeight = getSize().height;
                   //image = createImage(getSize().width,getSize().height);
                   tickerTape.initImage(sWidth, sHeight);
                   //gr=image.getGraphics();
         public void paint(Graphics g)
    update(g);
         public synchronized void update(Graphics g)
              //gr.clearRect(0, 0, d.getSize().width, d.getSize().height);
              //gr.setColor(bgCo);
              //gr.drawRect(0, 0, d.getSize().width - 1, d.getSize().height - 1);
              //gr.fillRect(0, 0, d.getSize().width, d.getSize().height);
              //g.drawImage(image, 0, 0, this);
              if (Ticker.LOADING_DATA) {
                   System.out.println("Refreshing data. Please wait....");
                   return;
              try {
                   if(image==null)
                        int sWidth = getSize().width;
                        int sHeight = getSize().height;
                   //image = createImage(getSize().width, getSize().height);
                        tickerTape.initImage(sWidth, sHeight);
                   //if (tickerTape.cParamsHeight() != lastS.height|| tickerTape.cParamsWidth() != lastS.width)
                   if (getSize().height != lastS.height|| getSize().width != lastS.width)
                   createParams();
                   if (tickerTape.getDisplayItems().size() > 0) {
                        //System.out.print("lastS.width: " + lastS.width + " lastS.height: " + lastS.height + "\n");
                        tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                        if (display_URL) {
                             int k = mouseX;
                             //System.out.println("k=" + k + " messageX=" + messageX);
                             if (k > messageX) {
                                  //System.out.println("(k > messageX) is true!!");
                                  //System.out.println("messageCount----> " + messageCount);
                                  messageCount = tickerTape.displayItemsCnt;
                                  k -= messageX;
                                  switch (this.mouseEvent) {
                                  case TickerTape.SCROLL_LEFT:
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       // for (int i1 = 0; i1 <= messageCount - 1; i1++)
                                       // i += ((Integer) msgsW.elementAt(i1)).intValue();
                                       // if (k >= i)
                                       // continue;
                                       // messageIndex = i1;
                                       // break;
                                       // break;
                                  if (this.mouseEvent == MOUSE_CLICK) {
                                       // showStatus((String)
                                       // msgsURL.elementAt(messageIndex));
                        //Font itemFont = null;
                        //FontMetrics fontMetrics = null;
                        //Color textColor = null;
                        //Vector msgs = tickerTape.getDisplayItems();
                                  switch (tickerTape.getScrollDirection()) {
                                  case TickerTape.SCROLL_LEFT:
                                       tickerTape.moveLeft(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       tickerTape.moveRight(messageX,messageY,ItemToDisplay);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_UP:
                                  case TickerTape.SCROLL_DOWN:
                                       tickerTape.moveDown(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       //g.drawImage(image, 0, 0, this);
                                       break;
                   }     else {
                        int sWidth = getSize().width;
                        int sHeight = getSize().height;
                             //image = createImage(getSize().width, getSize().height);
                        tickerTape.initImage(sWidth, sHeight);
                             //gr=image.getGraphics();
                             tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                             g.drawImage(image, 0, 0, this);
              } catch (Exception e) {
                   e.printStackTrace();
         public Ticker()
              messageCount = 1;
              // msgs = new Vector();
    //          msgsW = new Vector();
    //          msgsURL = new Vector();
              active = false;
              lastS = new Dimension(1, 1);
              display_URL = false;
         public void run()
              Thread.currentThread().setPriority(1);
              HBT = new heartBeatThread();
              HBT.start();
              HBT.resetTimer();
              System.out.println("[" + Version + "] :1. Running LATEST version!!!");
              System.out.println("[" + Version + "] :2. 25 JULY 2008,5:14:38PM!!!");
              int TimeoutCount = 0;
              //System.out.println("ITEMS : " + tickerTape.getDisplayItems().size());
    //          diVector = tickerTape.getDisplayItems();
    //          messageCount = tickerTape.displayItemsCnt;
    //          for (int index = 0; index < messageCount; index++)
    //               dispItem = diVector.elementAt(index);
    //               msgsURL.addElement(dispItem.getLink());
              DisplayItem disItem= new DisplayItem();
              txtCo = disItem.readColor("250,250,0", bgCo);
              linkCo = disItem.readColor("180,25,21", bgCo);
              bgCo = tickerTape.getBgColor();
    //          int tempCnt = 0;
              while(active)
                   nextPos();
                   try
                        if (messageY == (lastS.height / 2))
                             Thread.sleep(1000);
                        //Thread.sleep(50L);
                        Thread.sleep(this.milliSeconds);
                   }catch (InterruptedException _ex){     }
                   if(isSocket)
                             if (bStop)
                                  flag = false;
                                  break;
                             if ((socket == null) && (!(HBT.getTimeout())) && (bStop==false))
                                  try
                                       // socket = new Socket(host, 10000);
                                            try
                                                 //System.out.println("Ticker::host=["+host+"]");
                                                 //socket = new Socket(host, 10000);
                                                 socket = new Socket("172.18.20.123", 10000);
                                                 } catch(UnknownHostException unknownHost){
                                                      System.err.println("You are trying to connect to an unknown host!");
                                                 catch(IOException ioException){
                                                      ioException.printStackTrace();
                                       if (socket != null)
                                            System.out.println("If Socket is not null..");
                                            // if (UserRef=="")
                                            // UserRef = socket.getLocalAddress().getHostAddress();
                                            input = new DataInputStream(socket.getInputStream());
                                            output = new PrintStream(socket.getOutputStream());
    //                                        if(output != null)
    //                                             output.println('\001'+""+'\007'+0+'\007'+0+'\007'+0+'\002'+'\003'+""+'\007'+BrokerID+'\007'+SessionID+'\007'+Version+'\007'+'\004'+'\000');
                                            output.flush();
                                            sTmp = '\001'+"1002"+'\007'+1+'\007'+0+'\007'+0+'\002'+'\003'+""+'\007'+SendStr+'\004'+'\000';
                                            output.println(sTmp);
                                            output.flush();
    //                                        sendRequest();
                                       else
                                            isSocket = false;
                                            System.out.println("[" + Version + "] : Refresh Interval Set = [" + intSleepTimer + "]");
                                            sendPullRequest();
                                  } catch (IOException e)
                                       isSocket = false;
                                       System.out.println("[" + Version + "] : Refresh Interval Set = [" + intSleepTimer + "]");
                             try
                                  if ((socket != null) && (input != null))
    //                              System.out.println("HeartBeat True " + input.available());
                                       //while (input.available()>0)
                                       while (input.available() > 0)
                                            if (!bLoopThread)
                                                 break;
                                            TimeoutCount = 0;
                                            bRead = input.read();
                                            if (bRead != 0)
                                                 feed += (char)bRead;
                                            else if (bRead == 0)
                                                 try
                                                      dissectFeed(feed);
    //                                                  System.out.println("feed = [ " +  feed);
                                                 } catch (StringIndexOutOfBoundsException e)
                                                      e.printStackTrace();
    //                                             if (!(bSelfKill))
    //                                                  sendRequest();
                                                 feed = "";
                             } catch (IOException e)
                                  try
                                       System.out.println(" Socket read error stream Error = " + e.getMessage() + " Will Retry.");
                                       socket.close();
                                       input.close();
                                       output.close();
                                  } catch (IOException ex)
                                       System.out.println("Socket Close Error");
                                  if (bLoopThread)
                                       sendPullRequest();
         public void destroy()
              bStop = true;
              flag = false;
              if(socket != null)
                   try
                        socket.close();
                        socket = null;
                   } catch (IOException e)
                        System.out.println("destroy:Socket Close Error");
    //          if (myThread != null)
    //               myThread.stop();
    //               myThread = null;
         public void start()
              if (!active)
                   t = new Thread(this);
                   active = true;
                   t.start();
                   bStop = false;
                   flag = true;
    //          if (myThread == null)
    //               myThread = new Thread(this);
    //               myThread.start();
              bLoopThread = true;
         public void stop()
              active = false;
              t = null;
              bLoopThread = false;
              if (socket != null)
                   try
                        socket.close();
                        socket = null;
                   } catch (IOException e)
                        System.out.println("stop:Socket Close Error");
    //          if (myThread != null)
    //               myThread.stop();
    //               myThread = null;
         public synchronized void nextPos()
              switch (tickerTape.getScrollDirection())
              case TickerTape.SCROLL_LEFT:
                   scrollLeftToRight();
                   break;
              case TickerTape.SCROLL_RIGHT:
                   scrollRightToLeft();
                   break;
              case TickerTape.SCROLL_UP:
                   scrollBottomToTop();
                   break;
              case TickerTape.SCROLL_DOWN:
                   scrollTopToBottom();
                   break;
         public void setDelay(long milliSeconds)
              this.milliSeconds = milliSeconds;
         public boolean mouseUp(Event event, int i, int j)
              if (this.mouseEvent == MOUSE_MOVE)
    //               if (this.scrollDirection == TickerTape.SCROLL_UP || this.scrollDirection == TickerTape.SCROLL_DOWN)
    //                    messageIndex = itemIndex;
    //                    // System.out.println("itemIndex=" + itemIndex);
    //               URL url = null;
    //               try
    //                    url_ = (String) msgsURL.elementAt(messageIndex);
    //                    url = new URL(url_);
    //               } catch (MalformedURLException ex)
    //                    ex.printStackTrace();
    //                    return false;
    //               } catch (Exception ex)
    //                    ex.printStackTrace();
    //                    return false;
    //               display_URL = true;
    //               repaint();
    //               // System.out.println("messageIndex=" + messageIndex + " url: " + url_);
    //               getAppletContext().showDocument(url, "_");
              return true;
         @SuppressWarnings("deprecation")
         public boolean mouseEnter(Event event, int i, int j)
              try
                   if (this.mouseEvent == MOUSE_CLICK)
                        t.suspend();
                   else
                        flag = false;
                        //stop();
                        //t.suspend();
              } catch (Exception e)
                   e.printStackTrace();
                   return false;
              display_URL = true;
              // System.out.println("MouseEnter: " + messageIndex + " " + display_URL);
              repaint();
              return true;
         @SuppressWarnings("deprecation")
         public boolean mouseExit(Event event, int i, int j)
              try
                   flag = true;
                   //start();
                   //t.resume();
              } catch (Exception e)
                   e.printStackTrace();
                   return false;
              display_URL = false;
              repaint();
              // System.out.println("mouseExit " + display_URL);
              return true;
         //public boolean mouseMove(Event event, int i, int j)
              //mouseX = i;
              //display_URL = true;
              // System.out.println("MouseMove: " + messageIndex + " " + display_URL);
              //repaint();
              //return true;
         public synchronized void scrollRightToLeft()
              if(flag){
                   messageX -= increment;
                        //tickerTape.scrollRight(messageX);
                        repaint();
         public synchronized void scrollLeftToRight()
              messageX += increment;
              // System.out.println("X=" + messageX);
              if (messageX > lastS.width + tickerTape.getDisplayStringWidth())
                   // System.out.println("X=" + messageX + " width=" + lastS.width + " mW=" + messageW);
                   messageX -= (lastS.width + tickerTape.getDisplayStringWidth());
                   // messageX = 0;
                   // System.out.println("X=" + messageX);
              repaint();
         public synchronized void scrollBottomToTop()
              messageX = 10;
              messageY -= increment;
              if (messageY < 0)
                   messageY = lastS.height;
                   itemIndex += 2;
                   if (itemIndex >= messageCount - 1)
                        itemIndex = 0;
              repaint();
         public synchronized void scrollTopToBottom()
              messageX = 10;
              messageY += increment;
              if (messageY > lastS.height)
                   messageY = 0;
                   itemIndex += 2;
                   if (itemIndex >= messageCount - 1)
                        itemIndex = 0;
              repaint();
         public void sendRequest()
              if (bSelfKill)
                   return;
              //sTmp = '\001'+"0"+'\007'+0+'\007'+0+'\007'+0+'\002'+'\003'+""+'\007'+BrokerID+'\004'+'\000';
    //          System.out.println("SendRequest sTmp=["+sTmp+"],SendID=>[" + SendID + "],SendX => [" + SendX + "],SendY => [" + SendY + "],SendZ => [" +
    //          SendZ + "],UserRef => [" + UserRef + "],SendStr => [" + SendStr + "]");
              // output.println(sTmp);
              // if (SendZ>0) SendZ = 0;
              // sTmp = '\001'+"1002"+'\007'+1+'\007'+0+'\007'+0+'\002'+'\003'+""+'\007'+SendStr+'\004'+'\000';
         // output.println(sTmp);
              System.out.println("sendRequest " + sTmp);
         public void sendPullRequest()
              System.out.println("sendPullRequest() is Called");
              if (bSelfKill)
                   return;
              String strResult = "";
              URL url;
              ObjectOutputStream outputToServlet = null;
    //          sTmp = "" + '\001' + 1002 + '\007' + 2 + '\007' + 0 + '\007' + 0 + '\002' + '\003' + 3200 + '\007' + '\004' + '\000';
              sTmp = '\001'+"1002"+'\007'+2+'\007'+0+'\007'+0+'\002'+'\003'+""+'\007'+SendStr+'\004'+'\000';
    //          System.out.println("sendPullRequest " + sTmp);
              try
    //               url = new URL(getCodeBase().getProtocol()+"://"+getCodeBase().getHost() + "/my_FastFeed.jsp");
                   System.out.println(getCodeBase());
                   url = new URL("http://"+getCodeBase().getHost() + "/my_FastFeed.jsp");
                   System.out.println(url);
                   URLConnection URLConn = url.openConnection();
                   URLConn.setDoInput(true);
                   URLConn.setDoOutput(true);
                   URLConn.setDefaultUseCaches(false);
                   URLConn.setRequestProperty("Content-Type", "application/octet-stream");
                   outputToServlet = new ObjectOutputStream(URLConn.getOutputStream());
                   outputToServlet.writeObject(sTmp);
                   outputToServlet.flush();
                   outputToServlet.close();
                   InputStream inputstream = URLConn.getInputStream();
                   for (int j = inputstream.read(); j != -1; j = inputstream.read())
                        if (j == 1)
                             strResult = "";
                             // msgStart = true;
                        strResult = strResult + (char) j;
                        System.out.println("strResult>> " + strResult);
                        if (j == 4)
                             break;
                   inputstream.close();
                   sleepLoop = 0;
              } catch (IOException _ex)
                   System.out.println("sendPullRequest:IOException : " + _ex.getMessage());
              if (strResult != null)
                   if ((strResult.indexOf('\001') == -1) || (strResult.indexOf('\002') == -1) || (strResult.indexOf('\003') == -1) || (strResult.indexOf('\004') == -1))
                   else
                        dissectFeed(strResult);
         public void displaySysTime(String sTime)
         public String dissectFeed(String sFeed) throws StringIndexOutOfBoundsException, NumberFormatException
              //System.out.println("Feed>"+sFeed);
              try
                   if ((sFeed.indexOf('\001') == -1) || (sFeed.indexOf('\002') == -1) || (sFeed.indexOf('\003') == -1) || (sFeed.indexOf('\004') == -1))
                        return sFeed;
                   sHeader = sFeed.substring(sFeed.indexOf('\001') + 1, sFeed.indexOf('\002'));
                   sData = sFeed.substring(sFeed.indexOf('\003') + 1, sFeed.indexOf('\004'));
                   sFirst=sData.substring(2, 10);
                   //System.out.println("sHeader => [" + sHeader + "]");
                   //System.out.println("sData => [" + sData + "]");
                   String parts[] = sData.split("\\^");
                   if(parts.length == 1)
                        return "";
                   if(sFirst.equals("Consumer")){
                        Ticker.FIRST_LINE = true;
                   //System.out.println("parts.length--->>" + parts.length);
                   if (parts != null && parts.length > 0)
                        Ticker.LOADING_DATA = true;
                        int position = 0;
                        if (Ticker.FIRST_LINE)
                             // INDEX + ITEM NAME + VALUE + CHANGE
                             for (int i = 0; i < parts.length; i += 4)
                                  //System.out.println("FIRST LINE PARTS LENGTH : " + parts.length + " i = " + i);
                                  if (parts.length < i + 4)
                                       break;
                                  if(parts[i + 3].equals("SCO"))
                                       DisplayItem displayItemText = new DisplayItem();
                                       displayItemText.setText(parts[i + 1]); // ITEM NAME
                                       if(parts[i].equals("A1")){displayItemText.setItemIndex(9001);}
                                       else if(parts[i].equals("A2")){displayItemText.setItemIndex(9002);}
                                       else if(parts[i].equals("A3")){displayItemText.setItemIndex(9003);}
                                       else if(parts[i].equals("A4")){displayItemText.setItemIndex(9004);}
                                       else if(parts[i].equals("A5")){displayItemText.setItemIndex(9005);}
                                       else if(parts[i].equals("A6")){displayItemText.setItemIndex(9006);}
                                       tickerTape.AddDisplayItem(displayItemText, " XXXXX", position);
                                       position++;
                                       DisplayItem displayItemValue = new DisplayItem();
                                       displayItemValue.setText(parts[i + 2]); // ITEM VALUE
                                       if(parts[i].equals("A1")){displayItemText.setItemIndex(9001);}
                                       else if(parts[i].equals("A2")){displayItemText.setItemIndex(9002);}
                                       else if(parts[i].equals("A3")){displayItemText.setItemIndex(9003);}
                                       else if(parts[i].equals("A4")){displayItemText.setItemIndex(9004);}
                                       else if(parts[i].equals("A5")){displayItemText.setItemIndex(9005);}
                                       else if(parts[i].equals("A6")){displayItemText.setItemIndex(9006);}
                                       tickerTape.AddDisplayItem(displayIt

    Two bits of advice:
    1) Pare down your code to no more than 30-50 lines. Enough to compile and show the problem, but not so much as to make our eyes bleed, and for no one to want to read your post or help you.
    2) You would be wise not to state that your problem is "urgent". Even if it is urgent to you, realize that it is not urgent to us. Many here take offense to this as it implies to them that a) the poster thinks that his post is more important than everyone else's, and b) that the poster wants to put pressure on the volunteers who come here to help on their own free time. Just a friendly word of advice.
    I'll be happy to help when you've posted a reasonable amount of code. Good luck!

  • Marking upcoming events?

    Hello,
    In this code i'd like to mark the upcoming event with a ">"
    Its a RMS that holds entries of a diary with time and a sentence.
    So the output is like:
    2006-10-19 12:00 day after tomorrow
    '>' 2006-10-18 12:00 tomorrow
    2006-10-17 11:19 today
    2006-10-16 23:00 Yesterday
    2006-10-15 09:00 day before yesterday
    As you can see the marker is set at the next upcoming event, so my question is do I need a thread that keeps track of the different entries ?
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.rms.*;
    import java.util.*;
    public class LogB extends MIDlet implements CommandListener {
        private Display d;
        private List list;
        private Form newEvent;
        private Form checkEvent;
        private Form futEvent;
        private TextField newText;
        private TextField futText;
        private DateField date;
        private DateField nDate;
        private Command exitC;
        private Command saveC;
        private Command backC;
        private Command choiceC;
        private Command saveF;
        private RecordStore rtss;
        static final String REC_STORE = "Evts";
        public LogB(){
        protected void destroyApp(boolean unconditional)
        throws MIDletStateChangeException {
            exitApp(); // call cleanup code
        protected void pauseApp(){
            // add pause code here
        protected void startApp()
        throws MIDletStateChangeException {
            if( d == null ){
                initApp(); // perform one-time initialization
            // add per-activation code here
        private void initApp(){
            d = Display.getDisplay( this );
            // add initialization code here
            exitC = new Command("Quit", Command.EXIT, 0);
            saveC = new Command("Save", Command.OK, 0);
            backC = new Command("Back", Command.BACK, 0);
            choiceC = new Command("OK", Command.OK, 0);
            saveF = new Command("Save", Command.OK, 0);
            list = new List(null, Choice.IMPLICIT, new String[] {
                "New Event",
                "Future Event",
                "Browse Events"
            }, new Image[] {
                null,
                null,
                null
            list.addCommand(exitC);
            list.addCommand(choiceC);
            newEvent = new Form("New Event");
            newEvent.append(newDate());
            newEvent.append(newText());
            newEvent.addCommand(backC);
            newEvent.addCommand(saveC);
            newEvent.setCommandListener(this);
            futEvent = new Form("Future Event");
            futEvent.append(futureDate());
            futEvent.append(futureText());
            futEvent.addCommand(backC);
            futEvent.addCommand(saveF);
            futEvent.setCommandListener(this);
            checkEvent = new Form("Log History");
            checkEvent.addCommand(exitC);
            checkEvent.addCommand(backC);
            checkEvent.setCommandListener(this);
            list.setCommandListener(this);
            d.setCurrent(list);
        private TextField newText() {
            if (newText == null) {
                newText = new TextField("Event", "", 25, TextField.ANY);
                newText.setLayout(Item.LAYOUT_2 | Item.LAYOUT_TOP);
            return newText;
        private DateField newDate() {
            if(nDate == null) {
                nDate = new DateField("Time", DateField.DATE_TIME);
                nDate.setLayout(Item.LAYOUT_2 | Item.LAYOUT_TOP);
            return nDate;
        private DateField futureDate() {
            if(date == null) {
                date = new DateField("Time/Date", DateField.DATE_TIME);
                date.setLayout(Item.LAYOUT_2 | Item.LAYOUT_TOP);
            return date;
        private TextField futureText() {
            if(futText == null) {
                futText = new TextField("Future Event", "", 25, TextField.ANY);
                futText.setLayout(Item.LAYOUT_2 | Item.LAYOUT_TOP);
            return futText;
        public void exitApp(){
            // add cleanup code here
            notifyDestroyed(); // destroys MIDlet
        public void commandAction(Command c, Displayable b) {
            if(c == exitC) {
                exitApp();
            } else if (c == list.SELECT_COMMAND || c == choiceC) {
                switch (list.getSelectedIndex()) {
                    case 0:
                        Display.getDisplay(this).setCurrent(newEvent);
                        break;
                    case 1:
                        Display.getDisplay(this).setCurrent(futEvent);
                        break;
                    case 2:
                        Display.getDisplay(this).setCurrent(checkEvent);
                        checkEvent.deleteAll(); //Rinses the display from old inputs
                        openRecord();
                        readRecords();
                        closeRecord();
                        break;
            } else if(c == backC) {
                Display.getDisplay(this).setCurrent(list);
            else if(c == saveC) {
                openRecord();
                try {
                    saveRecord();
                } catch(StringIndexOutOfBoundsException e) {}
                closeRecord();
            else if(c == saveF) {
                openRecord();
                try {
                    saveRecordF();
                } catch(StringIndexOutOfBoundsException e) {}
                closeRecord();
    //--------------Recordstore-----------------------------------------
        public void readRecords() {
            try {
                if (rtss.getNumRecords() > 0) {
                    Comparators comp = new Comparators();
                    RecordEnumeration res = rtss.enumerateRecords(null, comp, false);
                    while (res.hasNextElement())
                        checkEvent.append(new String(res.nextRecord()));
            } catch (Exception e) {}
        private void openRecord() {
            try {
                rtss = RecordStore.openRecordStore(REC_STORE, true);
            } catch (Exception e) {}
        private void saveRecord() throws StringIndexOutOfBoundsException {
            Calendar cal = Calendar.getInstance();
            cal.setTime(nDate.getDate());
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH)+1;
            int date = cal.get(Calendar.DATE);
            int hr = cal.get(Calendar.HOUR_OF_DAY);
            int mnt = cal.get(Calendar.MINUTE);
            String time = ""+year + "-" + ""+month + "-" + ""+date + " " + ""+hr + ":" + ""+mnt + " ";
            String st = "Time:  " + time + " Message: " + newText.getString();
            byte[] frec = st.getBytes();
            try {
                rtss.addRecord(frec,0,frec.length);
            } catch(Exception e) {}
        private void saveRecordF() throws StringIndexOutOfBoundsException {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date.getDate());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            int date = calendar.get(Calendar.DATE);
            int hr = calendar.get(Calendar.HOUR_OF_DAY);
            int mnt = calendar.get(Calendar.MINUTE);
            String time = ""+year +"-"+ ""+month + "-"+ ""+date + " "+ ""+hr + ":" + ""+mnt +" ";
            String st = "Time: " + time + " Message: " + futText.getString();
            byte[] frec = st.getBytes();
            try {
                rtss.addRecord(frec,0,frec.length);
            } catch(Exception e) {}
        private void closeRecord() {
            try {
                rtss.closeRecordStore();
            } catch (Exception e) {}
    //--------Comparator class ----------
    class Comparators implements RecordComparator {
        public int compare(byte[] rec1, byte[] rec2) {
            String str1 = new String(rec1), str2 = new String(rec2);
            int result = str1.compareTo(str2);
            if (result == 0)
                return RecordComparator.EQUIVALENT;
            else if (result > 0)
                return RecordComparator.PRECEDES;
            else
                return RecordComparator.FOLLOWS;
    }

    I am starting to wonder if it has to do with how many future events we have in the calendar (ie a lot)?
    We have a number of groups, each with their own calendar and wiki. The upcoming events seem to work for groups with a small number of calendar events. But not for the larger ones.
    maybe?

  • StringIndexOutOfBoundsException with charAt

    I am trying to determine whether or not a string contains digits before taking any action on it. I purposely set the string to letters to test the code. I am getting a StringIndexOutOfBoundsExceptionexception even though I am retrieving the length of the string first and using that. For example, for this string (kl), the length returns 2 but the charAt isn't able to retrieve the string at 1....what am I missing?
    String tempCC = "kl";
    //System.out.println("tempCC-->"+tempCC+"<--");
         String[] tempCCArray = new String[lengthOfCC];
         for( int subMemCount=0; subMemCount<lengthOfCC; subMemCount++ ){
                   tempCCArray[encryptCCArray] = tempCC.substring(subMemCount,subMemCount+1);
                   encryptCCArray++;
                   //subCount = subCount+2;
    String ccEncrypted = "";
    System.out.println("tempCCArray.length-->"+tempCCArray.length+"<--");
         for( int temp=0; temp<tempCCArray.length; temp++ ){
              System.out.println("tempCCArray["+temp+"]-->"+tempCCArray[temp]);
                   boolean isCCDigit = Character.isDigit(tempCCArray[temp].charAt(temp));
         System.out.println("value of check-->"+isCCDigit+"<--");
              if (Character.isDigit(tempCCArray[temp].charAt(temp))) {
              int tempMemNumVal = Integer.parseInt(tempCCArray[temp]);
              tempMemNumVal = tempMemNumVal*tempMemNumVal;
              tempMemNumVal = tempMemNumVal+4;
              String newTempMemNumVal = Integer.toString(tempMemNumVal);
              if (newTempMemNumVal.length()==1)
                        newTempMemNumVal = "0" + Integer.toString(tempMemNumVal);
              else
                        newTempMemNumVal = Integer.toString(tempMemNumVal);
              ccEncrypted = ccEncrypted + newTempMemNumVal;
    the error I get is :
    java.lang.StringIndexOutOfBoundsException: String index out of range: 1

    Well, a big problem may be that you are using temp to refer to the length of the array AND using it to reference the character index of a string. The latter use seems to be causing issues. If you separated everything into one character strings (sorry, array of strings), then charAt(1) IS out of bounds.
    Why not simply use a char[] array instead?
    BTW, I am not sure that I completely understand what you are trying to do. My guess is that you are splitting a string into an array of one character strings. However, there are a number of variables (lengthOfCC and encryptCCArray for example) that are not really explained or defined. So, the analysis may be a bit off.
    - Saish
    "My karma ran over your dogma." - Anon

  • StringIndexOutOfBoundsException using ARRAY data type

    Hi all.
    JDK 1.5.0_03, Oracle 9.2.0.4, 9i thin drivers.
    I'm trying to use the ARRAY data type to submit a large amount of data to a stored procedure. Unfortunatley I'm getting an error when using the oracleCAllableStatement.setArray method. I've successfully set up my types in the database, and I can create my StructDescriptor and ArrayDescriptor objects but that's as far as I get.
    Here's my code:
    connection = ConnectionManager.getRawConnection(DatabaseProperties.CSA_DB);
    connection.setAutoCommit(false);
    ARRAY array = getDatabaseArray(timeSeriesList, date, connection);
    String result = new String();
    statement = (OracleCallableStatement)connection.prepareCall("{call DATA_LOAD.ARCHIVE_TIMESERIES(?, ?)");
    statement.setARRAY(1, array);
    statement.registerOutParameter(2, OracleTypes.VARCHAR, result);
    statement.execute();
    LOG.info(result);
    connection.commit();
    The line highlighted is where it fails. The exception is below. Unfortunatley its a Java exception rather than a Oracle one so not much help there.
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 40
         at java.lang.String.charAt(Unknown Source)
         at oracle.jdbc.driver.OracleSql.handleODBC(OracleSql.java:123)
         at oracle.jdbc.driver.OracleSql.parse(OracleSql.java:69)
         at oracle.jdbc.driver.OracleConnection.nativeSQL(OracleConnection.java:1181)
         at oracle.jdbc.driver.OracleStatement.expandSqlEscapes(OracleStatement.java:6412)
         at oracle.jdbc.driver.OracleStatement.parseSqlKind(OracleStatement.java:6401)
         at oracle.jdbc.driver.OraclePreparedStatement.<init>(OraclePreparedStatement.java:152)
         at oracle.jdbc.driver.OracleCallableStatement.<init>(OracleCallableStatement.java:77)
         at oracle.jdbc.driver.OracleCallableStatement.<init>(OracleCallableStatement.java:48)
         at oracle.jdbc.driver.OracleConnection.privatePrepareCall(OracleConnection.java:1134)
         at oracle.jdbc.driver.OracleConnection.prepareCall(OracleConnection.java:988)
         at com.db.csa.systems.csa.timeseries.DataArchivedTimeSeriesProvider.archiveTimeseriesForDate(DataArchivedTimeSeriesProvider.java:46)
         at com.db.csa.experiments.TimeseriesArchiver.main(TimeseriesArchiver.java:26)
    I'm now completely stuck as short of decompiling the class that's throwing the exception I have no idea what's going on.
    Anyone got any ideas?
    Thanks, Rob
    Message was edited by:
    user470390

    Hi,
    Shouldn't:
    statement = (OracleCallableStatement)connection.prepareCall("{call DATA_LOAD.ARCHIVE_TIMESERIES(?, ?)");be this:
    statement = (OracleCallableStatement)connection.prepareCall("{call DATA_LOAD.ARCHIVE_TIMESERIES(?, ?)}");i.e. have a closing brace?
    - Mark

  • Java.lang.StringIndexOutOfBoundsException: String index out of range: -9

    working on a project and came across this exception during runtime.
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
         at java.lang.String.substring(Unknown Source)
         at SomethingIsWrong.main(SomethingIsWrong.java:17)
    I'm a bit confused. could anyone shed some light on what im doing wrong? i know it deals with my testingStrings method.
    import java.io.*;
    import java.util.*;
    public class SomethingIsWrong
         static Scanner console = new Scanner(System.in);
         public static void main(String[] args)
              Rectangle method = new Rectangle();
              method.width = 40;
              method.height = 50;
              System.out.println("myRect's area is " + method.area());
              System.out.println("Was it a car or a cat i saw?".substring(-9, 12)); // error here
              testingStrings();
              grades();
         public static void cat(File file)
                                       throws FileNotFoundException
              String line = null;
              Scanner inFile = new Scanner(new FileReader("myFile.txt"));
              try
                   while ((line = inFile.nextLine())!= null)
                        System.out.println(line);
                   return;
              }     finally
                        if (inFile != null)
                             inFile.close();
         public static void grades()
              char grade;
              int testScore = console.next().charAt(0);
              if (testScore < 90)
                   grade = 'A';
              else if (testScore < 80)
                   grade = 'B';
                   else if (testScore < 70)
                        grade = 'C';
                   else if (testScore < 60)
                        grade = 'D';
                   else grade = 'F';
              System.out.println("Grade = " + grade);
         public static void testingStrings()
              String original = new String();
              StringBuilder result = new StringBuilder("hi");
              int index = original.indexOf('a');
              result.setCharAt(0, original.charAt(0));
              result.setCharAt( 1, original.charAt(original.length()-1));
              result.insert(1, original.charAt(4));
              result.append(original.substring(1,4));
              result.insert(3, (original.substring(index, index+2) + " "));
              System.out.println(result);
    final class Rectangle
         public int width;
         public int height;
         public int area()
              int area = width * height;
              return area;
    }

    jtan wrote:
    working on a project and came across this exception during runtime.
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
         at java.lang.String.substring(Unknown Source)
         at SomethingIsWrong.main(SomethingIsWrong.java:17)The error message is telling you exactly what's wrong.
    At line 17 of SomethingIsWring.java, you are calling substring() and passing -9 as one of the parameters. If you read the docs for String and for that method, and if you understand the fundamentals of Java Strings, you'll know why that is a no-no.

  • StringIndexOutOfBoundsException from Mail Adapter

    Hi,
    We have configured a sender communication channel for the mail adapter, but when we receive an email we get the following error message:
    <i>error occured: exception caught during processing mail message; java.lang.StringIndexOutOfBoundsException: String index out of range: -1</i>
    Our configuration is the following:
    Transport Protocol:  IMAP4
    Message protocol:    (tried both)
    URL:                 imap://exchangeServerHost
    The emails we tested with are plain/text emails. We tried both with an XML document as the main body of the email and with the XML document as an attachment, but the error remains the same.
    If anyone has some ideas on how to resolve or troubleshoot this it would be appreciated.
    Thanks in advance,
    Erik.

    Thanks Ranjit...I fixed the error. It was the URL I was missing the inbox from the URL.
    Check the following thread:
    Email Adapter Throwing Error
    Message was edited by:
            Alaa Qasem

  • OBIEE11g: download report in pipeline (|) or charat (^) delimiter format

    Hi,
    Need help with following customer queries for OBIEE 11g:
    Can a report be downloaded in pipeline (|) delimiter format or charat (^) delimiter format.
    There was a Bug 12403932 : CUSTOMIZE DOWNLOAD FORMAT. Is it fixed in the 11.1.1.5?
    Thanks & Regards,
    Priyanka Sharma

    I noticed that in the moment that IDM is asking me if i want to save
    and where to save, i wasn't logged in IDM, so i'm able to see only the
    task that is executed with success and the list of users in the task
    but any CSV or request to save CSV file.The following method converts a finished report to a string in CSV format:
      public static String printReportsAsCSV(String taskName, String sep, Locale locale)
        throws WavesetException {
        TaskManager tm = Server.getServer().getTaskManager();
        RepositoryResult er = tm.getExtendedResult(taskName, null);
        if(er != null && er.hasNext()) {
          ReportRenderer rend = new ReportRenderer(locale);
          StringBuffer sb = new StringBuffer();
          while(er.hasNext()) {
            TaskResult tr = (TaskResult)er.next().getObject();
            WavesetResult res = tr.getResult();
            if(res != null && res.getResults() != null && res.getResults().size() > 0) {
              Report report = (Report)res.getResult("report");
              rend.renderToSeparatedText(report, sb, sep);
              return sb.toString();
        return null;
      }Usage example:
    System.out.println(printReportsAsCSV("All Admin Roles", ",", Locale.getDefault()));The report is stored in the repository as a TaskResult object, so you
    can also export it in XML form and process with XSL or something.
    Cheers,
    Vladimir

  • StringIndexOutOfBoundsException for ess~de~pdata Webdynpro

    Hi All,
              Need your help. I'm getting the following JAVA exception while I'm trying to Launch Personal Information --> Personal Data for Germany. I tried to test both the Iview (preview option) and Application "Per_Personal_DE" of Webdynpro "sap.com/essdepdata" and all resulted in the same exception. Everything being used is the standard SAP delivered ESS business package. Can anyone throw some light on this issue.
    java.lang.StringIndexOutOfBoundsException: String index out of range: 4
         at java.lang.String.substring(String.java:1441)
         at com.sap.xss.per.fc.persinfo.FcPersInfo.CreateOverview(FcPersInfo.java:929)
         at com.sap.xss.per.fc.persinfo.wdp.InternalFcPersInfo.CreateOverview(InternalFcPersInfo.java:820)
         at com.sap.xss.per.fc.persinfo.FcPersInfoInterface.CreateOverview2(FcPersInfoInterface.java:333)
         at com.sap.xss.per.fc.persinfo.FcPersInfoInterface.CreateOverview(FcPersInfoInterface.java:316)
         at com.sap.xss.per.fc.persinfo.wdp.InternalFcPersInfoInterface.CreateOverview(InternalFcPersInfoInterface.java:327)
         at com.sap.xss.per.fc.persinfo.wdp.InternalFcPersInfoInterface$External.CreateOverview(InternalFcPersInfoInterface.java:475)
         at com.sap.xss.hr.per.de.personal.overview.BizCardsView.wdDoModifyView(BizCardsView.java:152)
         at com.sap.xss.hr.per.de.personal.overview.wdp.InternalBizCardsView.wdDoModifyView(InternalBizCardsView.java:342)
         at com.sap.tc.webdynpro.progmodel.generation.DelegatingView.doModifyView(DelegatingView.java:78)
         at com.sap.tc.webdynpro.progmodel.view.View.modifyView(View.java:337)
         at com.sap.tc.webdynpro.clientserver.cal.ClientComponent.doModifyView(ClientComponent.java:481)
         at com.sap.tc.webdynpro.clientserver.cal.ClientComponent.doModifyView(ClientComponent.java:488)
         at com.sap.tc.webdynpro.clientserver.window.WindowPhaseModel.doModifyView(WindowPhaseModel.java:551)
         at com.sap.tc.webdynpro.clientserver.window.WindowPhaseModel.processRequest(WindowPhaseModel.java:148)
         at com.sap.tc.webdynpro.clientserver.window.WebDynproWindow.processRequest(WebDynproWindow.java:335)
         at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.executeTasks(AbstractClient.java:143)
         at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:299)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingStandalone(ClientSession.java:759)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:712)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:261)
         at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:149)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:46)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:387)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:365)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:944)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:266)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:160)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    Thanks in advance,
    Best Regards,
    Subhadip

    Hello Subhadip,
    I remember encountering this error ....but not sure whether we applied a note or fixed it in webdynpro....in webdynpro you have to goto the ess~per DC -> FcPersInfo Component Controller -> CreateOverView() method ...and you have to fix it there....
    Shikhil

  • Java.lang.StringIndexOutOfBoundsException: String index out of range: 8

    Hi Friends,
    I have a search window ,in one I/P Field i entered * and kept the default max hits to display as 100 records(This can be changed).
    Now when i click on Search i get 100 records being displayed,later when i change it to 150,200 Hits i am able to get them displayed(Records).
    But when i enter value greater than 200(i had entered 220) i am getting the following exception.
    java.lang.StringIndexOutOfBoundsException: String index out of range: 8
    Can anyone please help me out to resolve this issue.
    Thanks and regards,
    Chandrashekar.

    Hello Chandrashekar,
            It looks like in  the loop of number of records, you are fetching the record and processing the string either using charAt() method or subString method or any similar method.
    But in one of the record string after 200th record is having a string which when you are processing are having length less than 8.
    Say : String s = "Correct";
    will give StringIndexOutOfBoundsException: String index out of range: 8 as the length is only 7 and you are  cheking for char at position 8.
    Just check the processing you are doing within the record loop and also the records.
    Hope this helps.

  • Java.lang.StringIndexOutOfBoundsException

    Hello, why does the following program generate a java.lang.StringIndexOutOfBoundsException error when a file is opened:
    Cryptogram.java (main program)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    public class Cryptogram extends JFrame
      private static final Enigma codeMachine = new Enigma();
      private static final String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      private static final String frequentLetters = "JQXZKBVWFUYMPGCLSDHROANITE";
      private static final int numLetters = letters.length();
      private JFrame thisWindow;
      private JMenuItem openItem, saveItem, exitItem;
      private String pathName = "";
      private JTextField subFields[] = new JTextField[numLetters];
      private JLabel hintLabels[] = new JLabel[numLetters];
      private JTextArea textAreaIn, textAreaOut;
      public Cryptogram()
        super("Cryptogram Solver");
        thisWindow = this;
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        FileAction fileAction = new FileAction();
        openItem = new JMenuItem("Open...");
        openItem.setMnemonic('O');
        openItem.addActionListener(fileAction);
        saveItem = new JMenuItem("Save...");
        saveItem.setMnemonic('S');
        saveItem.addActionListener(fileAction);
        saveItem.setEnabled(false);
        exitItem = new JMenuItem("Exit");
        exitItem.setMnemonic('x');
        exitItem.addActionListener(fileAction);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        JMenu decodeMenu = new JMenu("Decode");
        decodeMenu.setMnemonic('D');
        DecodeAction decodeAction = new DecodeAction();
        JMenuItem decodeItem = new JMenuItem("Decode");
        decodeItem.setMnemonic('D');
        decodeItem.addActionListener(decodeAction);
        JMenuItem clearItem = new JMenuItem("Clear");
        clearItem.setMnemonic('C');
        clearItem.addActionListener(decodeAction);
        JMenuItem encodeItem = new JMenuItem("Encode");
        encodeItem.setMnemonic('R');
        encodeItem.addActionListener(decodeAction);
        decodeMenu.add(decodeItem);
        decodeMenu.add(clearItem);
        decodeMenu.add(encodeItem);
        menuBar.add(fileMenu);
        menuBar.add(decodeMenu);
        setJMenuBar(menuBar);
        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(100, 81));
        p1.setLayout(new GridLayout(3, 1, 3, 3));
        p1.add(new JLabel("Code letter:", JLabel.RIGHT));
        p1.add(new JLabel("Stands for:", JLabel.RIGHT));
        p1.add(new JLabel("Computer hints:", JLabel.RIGHT));
        int k;
        JPanel p2 = new JPanel();
        p2.setPreferredSize(new Dimension(569, 81));
        p2.setLayout(new GridLayout(3, 26, 3, 3));
        for (k = 0; k < numLetters; k++)
          p2.add(new JLabel(letters.substring(k, k+1), JLabel.CENTER));
        for (k = 0; k < numLetters; k++)
          JTextField tf = new JTextField();
          tf.setBackground(Color.yellow);
          tf.setHorizontalAlignment(JTextField.CENTER);
          p2.add(tf);
          subFields[k] = tf;
        clearSubs();
        for (k = 0; k < numLetters; k++)
          hintLabels[k] = new JLabel(" ", JLabel.CENTER);
          p2.add(hintLabels[k]);
        JPanel p3 = new JPanel();
        p3.setPreferredSize(new Dimension(80, 81));
        p3.setLayout(new GridLayout(3, 1, 3, 3));
        p3.add(new JPanel());   // filler
        JButton refresh = new JButton("Refresh");
        refresh.addActionListener(decodeAction);
        p3.add(refresh);
        Box b1 = Box.createHorizontalBox();
        b1.add(p1);
        b1.add(Box.createHorizontalStrut(10));
        b1.add(p2);
        b1.add(Box.createHorizontalStrut(10));
        b1.add(p3);
        JPanel p123 = new JPanel();
        p123.add(b1);
        Font font = new Font("Monospaced", Font.PLAIN, 16);
        textAreaIn = new JTextArea(20, 30);
        textAreaIn.setFont(font);
        textAreaIn.setLineWrap(true);
        textAreaIn.setWrapStyleWord(true);
        JScrollPane areaScrollPaneIn = new JScrollPane(textAreaIn);
        areaScrollPaneIn.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textAreaOut = new JTextArea(20, 30);
        textAreaOut.setFont(font);
        textAreaOut.setLineWrap(true);
        textAreaOut.setWrapStyleWord(true);
        textAreaOut.setEditable(false);
        JScrollPane areaScrollPaneOut = new JScrollPane(textAreaOut);
        areaScrollPaneOut.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        Box b2 = Box.createHorizontalBox();
        b2.add(areaScrollPaneIn);
        b2.add(Box.createHorizontalStrut(10));
        b2.add(areaScrollPaneOut);
        Container c = getContentPane();
        c.add(p123, BorderLayout.NORTH);
        c.add(b2, BorderLayout.CENTER);
      private void clearSubs()
        StringBuffer subs = new StringBuffer(numLetters);
        for (int k = 0; k < numLetters; k++)
          subFields[k].setText("-");
          subs.append("-");
        codeMachine.setSubstitutions(subs.toString());
      private void normalSubs()
        StringBuffer subs = new StringBuffer(numLetters);
        for (int k = 0; k < numLetters; k++)
          JTextField tf = subFields[k];
          String s = tf.getText();
          if (s.length() < 1)
            s = "-";
          else
            s = s.substring(0,1).toUpperCase();
            if (!Character.isLetter(s.charAt(0)))
              s = "-";
          tf.setText(s);
          subs.append(s);
        codeMachine.setSubstitutions(subs.toString());
      private void randomSubs()
        StringBuffer subs = new StringBuffer(letters);
        int k, n;
        char ch1, ch2;
        for (n = numLetters; n > 1; n--)
          k = (int)(n * Math.random());
          ch1 = subs.charAt(k);
          ch2 = subs.charAt(n-1);
          subs.setCharAt(k, ch2);
          subs.setCharAt(n-1, ch1);
        String s = subs.toString();
        for (k = 0; k < numLetters; k++)
          subFields[k].setText(s.substring(k, k + 1));
        codeMachine.setSubstitutions(s);
      public void setHints(String text)
        int k;
        codeMachine.countLetters(text);
        for (k = 0; k < numLetters; k++)
          int pos = codeMachine.getFrequencyPos(k);
          hintLabels[k].setText(frequentLetters.substring(pos, pos+1));
      /***************          Action Listeners         ****************/
      private class FileAction implements ActionListener
        public void actionPerformed(ActionEvent e)
          int result;
          String text;
          JMenuItem m = (JMenuItem)e.getSource();
          if (m == openItem)
            JFileChooser fileChooser = new JFileChooser(pathName);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            result = fileChooser.showOpenDialog(thisWindow);
            if (result == JFileChooser.CANCEL_OPTION)
              return;
            File file = fileChooser.getSelectedFile();
            if (file != null)
              pathName = file.getAbsolutePath();
            EasyReader fileIn = new EasyReader(pathName);
            if (fileIn.bad())
              JOptionPane.showMessageDialog(thisWindow, "Invalid File Name",
                          "Cannot open " + pathName, JOptionPane.ERROR_MESSAGE);
            StringBuffer buffer = new StringBuffer((int)file.length());
            char ch;
            while ((ch = fileIn.readChar()) != '\0')
              buffer.append(ch);
            fileIn.close();
            saveItem.setEnabled(true);
            text = buffer.toString();
            textAreaIn.setText(text);
            setHints(text);
            textAreaOut.setText(codeMachine.decode(text));
          else if (m == saveItem)
            JFileChooser fileChooser = new JFileChooser(pathName);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            result = fileChooser.showSaveDialog(thisWindow);
            if (result == JFileChooser.CANCEL_OPTION)
              return;
            File file = fileChooser.getSelectedFile();
            if (file != null)
              pathName = file.getAbsolutePath();
            EasyWriter fileOut = new EasyWriter(pathName);
            if (fileOut.bad())
              JOptionPane.showMessageDialog(thisWindow, "Invalid File Name",
                          "Cannot create " + pathName, JOptionPane.ERROR_MESSAGE);
            text = textAreaOut.getText();
            fileOut.print(text);
            fileOut.close();
          else if (m == exitItem)
            System.exit(0);
      private class DecodeAction implements ActionListener
        public void actionPerformed(ActionEvent e)
          String cmd = ((AbstractButton)e.getSource()).getActionCommand();
          if ("Refresh".equals(cmd) || "Decode".equals(cmd))
            normalSubs();
          else if ("Clear".equals(cmd))
            clearSubs();
          else if ("Encode".equals(cmd))
            randomSubs();
          textAreaOut.setText(codeMachine.decode(textAreaIn.getText()));
      /***************                  main             ****************/
      public static void main(String[] args)
        Cryptogram window = new Cryptogram();
        window.addWindowListener(new WindowAdapter()
          { public void windowClosing(WindowEvent e) { System.exit(0); }});
        window.setBounds(30, 30, 800, 600);
        window.show();
    Enigma.java
    import java.util.*;
    public class Enigma
         private String lookupTable;
         private int[] letterCount;
         private static String frequentLetters="JQXZKBVWFUYMPGCLSDHROANITE";
         public Enigma()
              lookupTable="--------------------------";
              letterCount=new int[26];
         public void setSubstitutions(String lookupTable) {
              this.lookupTable = lookupTable;
         public String decode(String text)
              String decoded="";
              for(int i=0;i<text.length();i++)
                   if(Character.isLetter(text.charAt(i)))
                        decoded+=lookupTable.charAt((int)text.toLowerCase().charAt(i)-97);
                        if(Character.isUpperCase(text.charAt(i)))
                             Character.toUpperCase(decoded.charAt(decoded.length()-1));
                   else
                        decoded+=text.charAt(i);
              return decoded;
         public void countLetters(String text)
              Arrays.fill(letterCount, 0);
              for(int i=0;i<text.length();i++)
                   if(Character.isLetter(text.charAt(i)))
                   letterCount[((int)Character.toLowerCase(text.charAt(i)))-97]++;
         public int getFrequencyPos(int k)
              char letter=(char)(k+97-1);
              return frequentLetters.indexOf(letter);
    }The specific error:
    Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
         at java.lang.String.substring(Unknown Source)
         at Cryptogram.setHints(Cryptogram.java:214)
         at Cryptogram$FileAction.actionPerformed(Cryptogram.java:254)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.AbstractButton.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and a text file known to generate this issue:
    Okjcwkn Wusln yox ckbogcnwi gs fvffcwx, oki nbws opp yzrnw ck bsizovpcjx. Nbws pctwi ck nbw Xozob Iwxxwzn oki nzotwpwi gs Jofwprn. Nbw jpcfonw re nbw Xozob cx xvjb nbon nbw ckbogcnoknx botw nr pctw wpxwybwzw, xr jwznock ozwox re nbw iwxxwzn ozw jvpnctonwi gs czzcnoncrk. Nbw lszofcix ozw o zokuw re frvknockx gwnywwk Ezokjw oki Xlock. Nbw Wuslncokx gvcpn nbw lszofcix ck nbw xbolw re bvuw nzcokuvpoz jvgw.
    Nbw Uzwwdx ywzw o bcubps xjvplnvzwi lwrlpw, oki ycnbrvn nbwf yw yrvpik'n botw bcxnrzs. Nbw Uzwwdx opxr boi fsnbx. O fsnb cx o ewfopw frnb. Rkw fsnb xosx nbon nbw frnbwz re Ojbcppwx icllwi bcf ck nbw zctwz Xnska vkncp bw gwjofw cknrppwzogpw. Ojbcppwx ollwozx ck Nbw Cpcoi, gs Brfwz. Brfwz opxr yzrnw Nbw Riicns, ck ybcjb Lwkwprlw yox nbw poxn bozixbcl nbon Vpsxxwx wkivzwi rk bcx mrvzkws. Ojnvopps, Brfwz yox krn yzcnnwk gs Brfwz, gvn gs okrnbwz fok re nbon kofw.
    Xrjzonwx yox o eofrvx uzwwd nwojbwz ybr ywkn ozrvki uctcku lwrlpw oitcjw. Nbws dcppwi bcf. Xrjzonwx icwi ezrf ok rtwzirxw re ywiprjd. Oenwz bcx iwonb, bcx jozwwz xveewzwi o izofoncj iwjpckw.
    Ck nbw Rpsflcj Uofwx, Uzwwdx zok zojwx, mvflwi, bvzpwi nbw gcxjvcnx, oki nbzwy moto. Nbw zwyozi nr nbw tcjnrz yox o jrzop yzwonb.
             Ezrf "Okuvcxbwi Wkupcxb" gs Zcjbozi Pwiwzwz.Thanks! :)
    Edited by: John_Musbach on Feb 27, 2008 11:55 AM

    I fixed the funfunction like so:cti
    public int getFrequencyPos(int k)
              //char letter=(char)(k+97-1);
              //return frequentLetters.indexOf(letter);
              int countOfK=letterCount[k];
              Arrays.sort(letterCount);
              for(int i=0;i<letterCount.length;i++)
                   if(countOfK==letterCount)
                        return i;
              return 0;

Maybe you are looking for

  • How to create a Tone folder in itunes 11.0.4 to add ringtone

    firstly how to convert an mp3 file or .mp3 to .mAr file and second one in my itunes11.0.4 version there is no "TONES" named folder shown so if i convert mp3 to ringtone where could i place?, so please tell how to make folder.

  • Merging Basic data View and Classification View in Material Master

    Hi, There is a requirement to append Classification View under Basic Data View and then finally to delete Classification View. As per my understanding, it is not possible. Please let me know if it is possible, if so, please let me know how is it poss

  • Will mountain lion and iOS 6 force me to use ICloud?

    Reading the previews of mountain lion and ios 6, I get the impression that I'm going to be forced to use ICloud.  Is this true?  I don't want to be in the Cloud. And I don't want apps like Twitter mining information from or sharing information with,

  • Change Region of existing HANA instance

    Hello, We are facing the following problem. We have a HANA cloud instance which by mistake we have opened in Asia Pacific region in AWS. The result is that we have increased latency due to the remote location. (We are accessing the instance mainly fr

  • How to add tables in JSP page dynamically?

    Hi all, I am Girish, i am new to Java. I want to create a html page. The main requirment in the page is ... Initialy the page will contains a table which will accepts some data. If the user want to enter some more information he can click one add but