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

Similar Messages

  • Trouble with charAt and nested for loops

    Hi,
    I have a programming assignment in which my goal is to write a program that reads a social security number written as contiguous digits (eg, 509435456; obtained via JOptionPane); uses charAt to obtain each character; and then prints each digit on a separate line, followed by a colon and the digit printed the number of times equal to its value. Thus the output for 509435456 would be:
    5:55555
    0:
    9:999999999
    4:4444
    3:333
    5:55555
    4:4444
    5:55555
    6:666666
    I'm also required to use a char variable for the inner loop control variable, and write the inner for loop as something along the lines of
    for(char index = '1'; index <= digit; index++) where digit is the char variable use to store the digit taken from the string.
    Here's what I have so far:
    import javax.swing.JOptionPane;
    public class Prog3a
         public static void main (String [] asd)
         String ssn = JOptionPane.showInputDialog("Que es tu SSN?");
         for (int rows = 0; rows < 9; rows++) //number of rows
                   char digit = ssn.charAt(rows) - '0';
                   System.out.print(digit + ":");
                   for (char index = 0; index < digit; index ++) //how many characters are going to be on each row
                             System.out.print(digit);
              System.out.println("");
    }Unfortunately, the char digit = ssn.charAt(rows) - '0'; errors on me, and only works when char is replaced with int. However, digit is no longer a char for the inner loop, and this fails to meet the requirements of the assignment. How can I assign the char without this "loss of precision"?

    Original Assignment:
    +3a. Write a program that reads a social security number written as contiguous digits (for instance, 509435456), uses the charAt method to obtain each character and then prints each digit on a separate line followed by a colon and the digit printed the number of times equal to its value. Thus the output for 509435456 would be+
    +5:55555+
    +0:+
    +9:999999999+
    +4:4444+
    +3:333+
    +5:55555+
    +4:4444+
    +5:55555+
    +6:666666+
    The string should be read using JOptopnPane.
    +Use a char variable, e.g., index, for the inner loop control variable and write the inner for loop as for(char index = '1'; index <= digit; index++) where digit is the char variable use to store the digit taken from the string.+
    +3b. Write the program so that index, the inner loop index, is an int variable. This means you must convert the character assigned to digit to an int.+
    Is that any help? It's as much as I know.

  • StringIndexOutOfBoundsException with SAX

    Hi,
    Am facing this error: "StringIndexOutOfBoundsException - string index out of range -84" while parsing a file using Java SAX parser
    I am hitting google adwords API and from the response data, am writing a xml which i then parse to get its data and put into database.
    I think there is some bad data in the response, but am not sure how to handle this error...i need to parse the file. Also, the file size is bit huge (more than 30 mb) and using DOM gives an out of memory error, hence i have to use SAX
    Can anyone suggest a solution or workaround to this so that am able to successfully parse the complete file

    With very little to go on, let me risk a guess.
    Check very carefully how you have implemented the characters method. There is no guarantee that the parser will only call that method once. It may make several calls to the method in order to process what looks to you like it should be a single String. Check the javadocs for that method and you will see a suggestion to use a StringBuilder or StringBuffer to which you append the contents of each call. There is a version of the append method that uses the same three parameters (char[], int, int) as is provided in the characters method. When you get to the endElement method, you can use toString() to convert the StringBuilder or StringBuffer to a String.
    A suggestion. Since you are processing a large file, instantiate the SringBuilder or StringBuffer once, perhaps in the constructor for the class that extends the ContentHandler interface. Specify a length in the constructor that is larger than the length of any of the Strings that will be processed. Then use "setLength( 0 )" in the startElement to reset the length without repeatedly creating a new object.
    Dave Patterson

  • Having a few difficulties with charAt...

    Hello,
    I am a beginner to Java. I know most of the basics and I am still in a learning process. I am trying to write a program that lets a user enter in any word and prints out the number of vowels and consonants (and any other character) in the word. My first problem is understanding the concept of what I am supposed to do. I am extremely confused. How am I suppose to know to know what word a user would write? I won't know which character positions to use unless I know the word, which is the hard part. Does anyone know how to write this program, and if so, how? I appreciate all help. Thank you!

    import java.io.*;
    public class test{
    public static void main(String[] args) {
    try{
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    // in is the object that allows things to be read from the user
         System.out.print("Please enter a string: ");
         String str = in.readLine(); // tells the system to accept user input
         System.out.println("This is the string typed by the user: "+str);
    // loop and char check is put into here
    }catch(Exception e){}
    this would read the user input and allow u to start ur program off wat you wan to do then is probably use the string.charAt() method in a for loop to cycle through all the letters in the given input and check wat type of char it is.. then print out ur results.
    so the program will like this:
    import java.io.*;
    public class test{
    public static void main(String[] args) {
    try{
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Please enter a string: ");
         String str = in.readLine();
         System.out.println("This is the string typed by the user: "+str);
         int vowel = 0;
         int consta = 0;
         for(int i = 0;i < str.length(); i++){
         char c = str.charAt(i);
         if((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u')) vowel++;
         // checks for vowels and increments counter.
         else if(!(c=='a')&&!(c=='e')&&!(c=='i')&&!(c=='o')&&!(c=='u')) consta++;
         // this conditions shud be true if not any vowel so must be constanent
         System.out.println("there were "+vowel+" Vowels and "+consta+" Constanents.");
    }catch(Exception e){}
    this should work for u... its a very simple example and you can use other things to check the chars but its a good place to start. you will need the change the if statements though if you want to check for more detail on the strings.

  • How do you strip out certain groups of characters from a String variable

    for exapmle...
    String date = "11-Feb-2005";
    String day;
    String month;
    String year;
    how would you strip out '11' from date to assign it to 'day', and 'Feb' to assign it to 'month' and '2005' to assign it to 'year'.
    in my program the variable 'date' will always be in the format of:
    ist two digits are numbers followed by '-'
    then three digits (letters) followed by '-'
    then four digits that are numbers.
    i think it has something got to do with charAt or something, im not sure how to do it.
    any ideas?

    yea i tried the first method and it works fine.
    thanks very much.
    also... i tried the other one and it outputs... 11 1 2005
    which means it works but you see i wanted to put the date in the format of...
    Calendar date = new GregorianCalendar(2005, Calendar.FEBRUARY, 11); so i can compare it to another Calender object to see which one is earlier.
    that is why i am doing it like this...
    Calendar date = new GregorianCalendar(+ year + ", Calendar." + month + ", " + day);
    for example...
    Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
    Calendar newyears = new GregorianCalendar(1999, Calendar.JANUARY, 1);
    // Determine which is earlier
    boolean b = xmas.after(newyears); // false
    b = xmas.before(newyears); // true
    anyways i am just curious.

  • Capital and small letters.

    Dears Sirs,
    For my UNI assignment I am generating an array of objects with length of the array is given by the user. Each object contains Name ,Age and income fields.I have done that.
    But there is a constraint. In the Name fieldtThe first character should be a capital letter and all remaining should be small letters.
    How can it be accomplished?
    I thought that
    1) I generate a capital character first time and store it in a variable. Next I generate a string of small letters. Later I append it.
    Or 2) If possible, I generate only a string of small letters then transform the first letter into capital letter.
    Please advise if the second option is possible in java. If so hoe to do that.
    Thanx,
    venkatcute

    The second option is easy; I suggest you have a look at the Javadoc of the String class, that's right here: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html - it has methods like toUpperCase and toLowerCase(); With charAt(0); you can get the first character of the String and then you can create a new String with the first character converted to uppercase.

  • How to get String after Certain Number of particular characters

    I want to get character after certain numbers's of particular character.
    For example following is String
    String testString = "||A|||B||D|R|T|||TEST|||||"
    I want to get "TEST" which is after 12 "|"
    How can I manupulate String to give me characters after 12 "|"
    I will appreciate any help.

    Loop over the string, looking at each char with charAt(itn index).
    Compare each char to '|'.
    If it matches, increment the counter.
    If the counter is 12, then take the substring from your current position in the string to the end.

  • Comparing characters

    I'm trying to make a program that will have the user enter a string of code, and then compare the first and last characters of the string to each other
         String text=reader.readLine("Enter string of text ");
              System.out.println(text.length());
              int numsave=text.length();
              int savechar1=text.charAt(1);
              System.out.println(savechar1); 
              int savechar2=text.charAt(numsave);
              System.out.println(savechar2);The thought behind the length statement would be to have it check how long it is, and then since it would be the length, it would be the index for the last character as well, but apparently that doesn't fly in java because it gives me and error on that line when I compile it.

    it checks the first character with
    charAt(1), which spits out a number, whereas its
    looking for actual characters when using endsWithLook at where you assign the value of savechar1. Is there anything in your code that tells the program you want it to make savechar1 an int? The program will make the type of savechar1 to be exactly what you tell it to be.
    Edit: I guess that's not what you were worried about. However, you would have found debugging to be much easier if you could see the actual charcter returned by charAt(1), instead of just the int representation
    As for using "endsWith", if you take a look at the charAt(int i) method in String, you'll see that it tells you the index numbers of the first and last characters in the String. What is the index number of the first character? (It's not 1 like you're saying above). What is the index number of the last character compared to String.length()?
    Edit: Oh, I guess Gino went ahead and told you straight out what the indexes should be.
    Message was edited by:
    Asbestos

  • Can i turn a series of integers such as 1000-1200  into a string to check

    can i turn a series of integers such as 1000-1200 into a string to check positions with charAt I need to scan numers 1000-9999 to add the digits 1+0+0+0=1 or 9+9+9+9=36 to find the ones that when the result ie 36 is rased to the 4th power equal the original number? I want to scan charAt(position) then add those 4 positions.please help me
    heres my code so farpublic class Poweroffour
        public static void main(String[] args)
        int number;     
         String numberS;
        int numtotal;
         int numtotalpoweroffour;
         int num1;
         int num2;
         int num3;
         int num4;
         for (number=1000;number<10000;number++)
              numberS=number;
              num1=numberS.charAt(1);
              num2=numberS.charAt(2);
              num3=numberS.charAt(3);
              num4=numberS.charAt(4);
                 numtotal=num1+num2+num3+num4;
                 numtotalpoweroffour=numtotal*numtotal*numtotal*numtotal;
                 if (numtotalpoweroffour==number)
                      System.out.println(number);
        }}

    public class Poweroffour
        public static void main(String[] args)
            int numb=0;
             int thou=0;
            int hund=0;
            int tens=0;
            int ones=0;
            int total;
            int count;
           for (numb=1000;numb<10000;numb++)
                thou = numb/1000;
                hund = (numb -(thou *1000))/100;
                tens = ((numb % 100)- ones)/10;
                ones = numb % 10;
                System.out.println( thou + " " + hund + " " + tens + " " + ones);
    }          

  • How would I find...

    Hey there, I am somewhat new to Java and I was wondering, if I had a string, how could I check it to see how many letters there are in it? Is there some sort of function to do this?

    You could manually iterate over the characters with charAt() and then test Character.isLetter on each one, incrementing a count if true.
    Or you could use regex's \p{Alpha}.
    The first one is probably faster (but probably not signifiantly so in most contexts), and simpler if you don't know regex.
    The second one leads to more compact code, and is more readable if you do know regex.

  • File processing failed with java.lang.StringIndexOutOfBoundsException:

    Hi
    I´m reading and sending files to an FTP server using SAP PI. I use file content conversion.
    Everything has been working fine for months - but now the server was changes to a new host. The only thing changed was the host/user and pass.
    But sending too the server fails with this error:
    File processing failed with java.lang.StringIndexOutOfBoundsException: String index out of range: -27
    Any body who has a clue??
    Reading files works ok. And i can transfer files to the FTP server with FileZilla without problems.

    In the file transfer by ftp:
    2011-10-03 17:27:08     Information     Transfer: "BIN" mode, size 737 bytes, encoding -.
    2011-10-03 17:27:08     Error     File processing failed with java.lang.StringIndexOutOfBoundsException: String index out of range: -27
    2011-10-03 17:27:08     Error     Adapter Framework caught exception: String index out of range: -27
    2011-10-03 17:27:08     Error     Delivering the message to the application using connection File_http://sap.com/xi/XI/System failed, due to: com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error occurred while connecting to the FTP server "nnn.nn.nnn.nnn:21": java.lang.StringIndexOutOfBoundsException: String index out of range: -27.
    Its on the adapter level. All mappings etc are fine. And as i write has been for months. The only thing changed are the FTP server

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

  • Please help with "while" "charAt" and "length"

    i'm trying to write a program that counts the number of each vowel in an inputed string of characters. i'm using a "while" statement, not a "for" statement, and i'm using a switch statement inside the "while"
    i'm having trouble getting the while statement right and i'm also struggling with using charAt and length.
    here's what i have so far:
    import cs1.Keyboard;
    public class mdlprog5
    public static void main(String[] args)
    String textLine;
    int aCount = 0;
    int eCount = 0;
    int iCount = 0;
    int oCount = 0;
    int uCount = 0;
    int nonVowel = 0;
    int charPosition = 0;
    char currentChar;
    System.out.println ("Enter a line of text.");
    textLine = Keyboard.readString();
    while (textLine.charAt(charPosition) < textLine.length())
    currentChar = textLine.charAt(charPosition);
    switch (currentChar)
    case 'A':
    aCount = aCount + 1;
    charPosition++;
    break;
    case 'E':
    eCount = eCount + 1;
    charPosition++;
    break;
    case 'I':
    iCount = iCount + 1;
    charPosition++;
    break;
    case 'O':
    oCount = oCount + 1;
    charPosition++;
    break;
    case 'U':
    uCount = uCount + 1;
    charPosition++;
    break;
    default:
    nonVowel = nonVowel + 1;
    charPosition++;
    anybody have any idea what i'm doing wrong??
    thanks in advance for your help

    venumadhavA,
    i don't understand what you're saying. could you
    please elaborate?
    Sudha,
    thanks for the idea, it worked great!This is more precise and is what enumadhavA suggested,
    import cs1.Keyboard;
    public class mdlprog5
    public static void main(String[] args)
    String textLine;
    int aCount = 0;
    int eCount = 0;
    int iCount = 0;
    int oCount = 0;
    int uCount = 0;
    int nonVowel = 0;
    int charPosition = 0;
    char currentChar;
    System.out.println ("Enter a line of text.");
    textLine = Keyboard.readString();
    textLine = textLine.toUpperCase();
    while (charPosition < textLine.length())
    currentChar = textLine.charAt(charPosition);
    switch (currentChar)
    case 'A':
    aCount = aCount + 1;
    break;
    case 'E':
    eCount = eCount + 1;
    break;
    case 'I':
    iCount = iCount + 1;
    break;
    case 'O':
    oCount = oCount + 1;
    break;
    case 'U':
    uCount = uCount + 1;
    break;
    default:
    nonVowel = nonVowel + 1;
    charPosition++;
    Hope this works fine.
    Sudha

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

  • Issue with adding Long charater field in custom table

    I have added a URL ( Internet address ) field ZZSSOURIADDR with data element AD_URI whose domain is long character and length 2048.On activation table gives an message in a log
       Field ZZSSOURIADDR does not have a preceding length field of type INT4.
    What needs to be done to remove this error?

    As specified in SAP documentation, this must be the last field, and the previous one must be the actual length field type INT2. (suggestion: use data element AD_URILNG)
    LCHR: Character string of any length, but has to be declared with a minimum of 256 characters. Fields of this type must be located at the end of transparent tables (in each table there can be only one such field) and must be preceded by a length field of type INT2. If there is an INSERT or UPDATE in ABAP programs, this length field must be filled with the length actually required. If the length field is not filled correctly, this may lead to a data loss in the LCHR field! A fields of this type cannot be used in the WHERE condition of a SELECT statement.
    If error message wasn't clear enough, then try a where-used in transparent table of the data element AD_URI.
    NB: You could also use in your development the central address, actual URL would be stored in ADR12 and only ADRNR is in your custom database table, more development (look for BAPI BUPA) but smaller database.
    Regards,
    Raymond

Maybe you are looking for

  • Ipod 5 wasn't updating new playlists.  Removed all music from iPod and ended up with 34 GB of OTHER.  How do I remove this without doing a full restore?

    iPod 5 was not adding new playlists when synching (plenty of space remained in memory for it).  This happened around the time of the new update.  I removed all music from the iPod and when I went to resync the selected playlists, my OTHER portion of

  • Help with an existing website

    i created this site about 15 years ago. it has since been maintained by someone else, and now it's back in my lap. I used a different program to design it then and i'm heck'a rusty at the whole thing. i need help with how to get access to the site. I

  • Website flash player problem

    Hi everyone, I have a website www.manwithvanlondon.com some times the browser crashes when loading the website and the error is due to flash player? Any help would be apriaciated. Thanks Dylan

  • Maven Auto deployment problems in Weblogic 10.0

    Hi All, Past two day's i am facing a exception in maven auto deployment process. I have given properly the configuration Tags(Shown below). I am able to send the deployment commands to weblogic but i am getting some run time exceptions. Please find b

  • JDBC Drivers Exception...........

    Hi: I am using Apache 1.3.26 + JBoss + Tomcat on my Web/APP Server and Oracle 9.1 on DB Server. I installed JDBC Drivers ojdbc14.jar, classes12.jar, nls_charset111.jar on my APPLICATION Server and SET the CLASSPATH accordingly. What all need to be do