Results 1 to 6 of 6
  1. #1
    dofo is offline Member
    Join Date
    Jul 2013
    Location
    Charlottesville, USA
    Posts
    12
    Rep Power
    0

    Default How to define a char that creates an out of bounds index exception

    Full disclosure: this is homework. I've been programming java in the context of a couple of college classes off and on over the course of a year or so. This assignment is about learning how to manipulate exceptions. I've got everything done except for what I think is one line of code that I can't get. I'm stuck.

    Here are the directions of the part that has me stumped:

    Originally, we were to set up the program to print the actual out of bounds exception that is thrown in a print statement that notifies the user of the exception. Then, it was changed so that:

    "In your print statement, replace the exception with the character that created the out of bounds index."

    The said print statement starts at line 35.

    I can't figure out how to define/assign, within the framework of the code, the char that creates the exception. I believe that I've got everything together except for this assignment currently commented out at line 30 of the code. Even if the whole program isn't completely correct, once I know conceptually how to make this assignment, I'll be able to figure out the rest to make it work. My idea is to figure out the last value of word.charAt(i) within the for loop which starts at line 27. This last value of i is what throws the exception and ends the loop. How can I assign that value to a char? I've looked at several javadocs and just can't seem to find a method or figure out the concept to make this work.

    Here is my code:


    Java Code:
    // ****************************************************************
    // CountLetters.java
    //
    // Reads a words from the standard input and prints the number of 
    // occurrences of each letter in that word.
    // ****************************************************************
    
    import java.util.Scanner;
    public class CountLetters
    {
        public static void main(String[] args)
        {
           int[] counts = new int[26];
           char charExcept;
           Scanner scan = new Scanner(System.in);
    
           //get word from user
           System.out.print("Enter a single word (letters only, please): ");
           String word = scan.nextLine();
          
           //convert to all upper case
           word = word.toUpperCase();
    
           //count frequency of each letter in string
           try
           {
               for (int i=0; i < word.length(); i++)
            {
                counts[word.charAt(i)-'A']++;
                //charExcept = ??;
            }
          }
          catch (ArrayIndexOutOfBoundsException exception)      
          {
              System.out.println("\n" /*+ charExcept */ + " is not a letter, Paco. \nWe did "
                      + "request letters only, now didn't we?\n "
                      + "\n\nAnyway, here's your count for the first part:");
          }
             
          //print frequencies
          System.out.println();
          for (int i=0; i < counts.length; i++)
              if (counts [i] != 0)
             System.out.println((char)(i +'A') + ": " + counts[i]);
          
          System.out.println("\nYou may think I'm rude, but my mother "
                  + "says I'm quite a catch.\n\n");
          }
    
    }
    Thank you for the help!
    Last edited by dofo; 07-18-2013 at 08:33 AM.

  2. #2
    dofo is offline Member
    Join Date
    Jul 2013
    Location
    Charlottesville, USA
    Posts
    12
    Rep Power
    0

    Default Re: How to define a char that creates an out of bounds index exception

    Nevermind, I figured it out. I could have sworn that I tried this already and it didn't work. I must have had the syntax entered wrong:

    Java Code:
    // ****************************************************************
    // CountLetters.java
    //
    // Reads a words from the standard input and prints the number of 
    // occurrences of each letter in that word.
    // ****************************************************************
    
    import java.util.Scanner;
    public class CountLetters
    {  
        static char charExcept;
        
        public static void main(String[] args)
        {
           int[] counts = new int[26];
           Scanner scan = new Scanner(System.in);
    
           //get word from user
          System.out.print("Enter a single word (letters only, please): ");
          String word = scan.nextLine();
          
          //convert to all upper case
          word = word.toUpperCase();
    
          //count frequency of each letter in string
          try
          {
            for (int i=0; i < word.length(); i++)
            {
                counts[word.charAt(i)-'A']++;
                charExcept = word.charAt(i+1);
            }
          }
          catch (ArrayIndexOutOfBoundsException exception)      
          {
              System.out.println("\n" + charExcept + " is not a letter, Paco. \nWe did "
                      + "request letters only, now didn't we?\n "
                      + "\n\nAnyway, here's your count for the first part:");
          }
          
          //print frequencies
          System.out.println();
          for (int i=0; i < counts.length; i++)
              if (counts [i] != 0)
             System.out.println((char)(i +'A') + ": " + counts[i]);
          
          System.out.println("\nYou may think I'm rude, but my mother "
                  + "says I'm quite a catch.\n\n");
          }
    }

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,846
    Rep Power
    19

    Default Re: How to define a char that creates an out of bounds index exception

    Does that work?
    Because you are only setting charExcept *after* the exception is thrown (that is that assignment will not happen).
    And aren't you setting it to the wrong character?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    dofo is offline Member
    Join Date
    Jul 2013
    Location
    Charlottesville, USA
    Posts
    12
    Rep Power
    0

    Default Re: How to define a char that creates an out of bounds index exception

    Quote Originally Posted by Tolls View Post
    Does that work?
    Because you are only setting charExcept *after* the exception is thrown (that is that assignment will not happen).
    And aren't you setting it to the wrong character?
    I'm not 100% sure I can tell you why it works, but it's working now. Feel free to copy/paste and run the code. I THINK it works because what you're looking for is the last value of int i in the for loop. You are correct that it it assigns the wrong character (wrong value of i) because of the exception, but being one spot short is easy enough to solve. You just add 1 to i and you'll be at the right character.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,846
    Rep Power
    19

    Default Re: How to define a char that creates an out of bounds index exception

    No, what I mean is charExcept is only used to hold the character that caused a problem so you can then append it to the exception message.
    Your logic at the moment seems to me to be:
    Java Code:
    for all characters
       increment the character count for that character.
       if it's not a character goto EXCEPTION.
       store the next character in charExcept
    EXCEPTION:
       print the value of charExcept.
    Now look at that.
    If the very first character is not a valid one then you will be printing 0...which is only rarely going to be correct.
    But even if it manages to get through the string the very last call to charAt should throw an IndexOutOfBoundsException, as you're trying to get a character that's not there.

    When all you have to do is assign charExcept as the first thing in the loop (and use the correct index).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    dofo is offline Member
    Join Date
    Jul 2013
    Location
    Charlottesville, USA
    Posts
    12
    Rep Power
    0

    Default Re: How to define a char that creates an out of bounds index exception

    You are correct. My haste and desire for sleep made for poor parameter testing. Thank you, once again, for the help! For anyone keeping score out there, here is code that seems to be working correctly:

    Java Code:
    // ****************************************************************
    // CountLetters.java
    //
    // Reads a words from the standard input and prints the number of 
    // occurrences of each letter in that word.
    // ****************************************************************
    
    import java.util.Scanner;
    public class CountLetters
    {  
        static char charExcept; // char that causes exception 
        static String space = ""; // string for when charExcept is a blank space
        
        public static void main(String[] args)
        {
           int[] counts = new int[26];
           Scanner scan = new Scanner(System.in);
    
           //get word from user
          System.out.print("Enter a single word (letters only, please): ");
          String word = scan.nextLine();
          
          //convert to all upper case
          word = word.toUpperCase();
    
          // count frequency of each letter in string and assign the 
          // char that causes the exception to be trhown
          try
          {
            for (int i=0; i < word.length(); i++)
            {
                charExcept = word.charAt(i);
                counts[word.charAt(i)-'A']++;
            }
          }
          
          // catches exception and reassign value of 'space' if char 
          // is a blank space
          catch (ArrayIndexOutOfBoundsException exception)      
          {
              if (charExcept == ' ')
              {
                  space = " (blank space)";
              }
              
              // print statment
              System.out.println("\nA " + charExcept + space + " is "
                      + "not a letter, Paco. \nWe did "
                      + "request letters only, now didn't we?\n "
                      + "\n\nAnyway, here's your count for the first part:");
          }
          
          //print frequencies
          System.out.println();
          for (int i=0; i < counts.length; i++)
              if (counts [i] != 0)
             System.out.println((char)(i +'A') + ": " + counts[i]);
          
          System.out.println("\nYou may think I'm rude, but my mother "
                  + "says I'm quite a catch.\n\n");
          }
    }
    Last edited by dofo; 07-18-2013 at 03:46 PM.

Similar Threads

  1. Array index out of bounds exception...
    By NinjaRobotPanda in forum Java 2D
    Replies: 2
    Last Post: 01-30-2013, 01:27 PM
  2. String Index Out of Bounds Exception
    By phyzix5761 in forum New To Java
    Replies: 4
    Last Post: 11-09-2012, 09:09 PM
  3. Help Array Index out of bounds exception
    By star400040 in forum New To Java
    Replies: 2
    Last Post: 12-10-2010, 10:24 PM
  4. array Index out of Bounds exception== 0
    By Allgorythm in forum New To Java
    Replies: 6
    Last Post: 02-11-2010, 04:02 PM
  5. Array Index Out of Bounds Exception
    By kool001 in forum New To Java
    Replies: 1
    Last Post: 12-03-2009, 07:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •