user102817
user102817

Reputation: 307

Java Method Confusion with Chars

I'm attempting to write a method that takes in a string and an array and print out the following...

--- Name is "Abe"---
Adorable
Beautiful
Elegant

--- Name is "bob"---
Beautiful
Outstanding
Beautiful

My code...

public static void printReport(String name, String[] sortedArray)
{
    System.out.println(name);
    char c = '\0';
    for (int i = 0; i <name.length()-1;i++)
    {
        c = name.charAt(i);
        int index = c-'A';
        System.out.println(sortedArray[index]);
    }
}
}

Where name is the... well name, and sortedArray is an array of 26 adjectives in alphabetical order. I'm attempting to use the numerical values of chars to print out the correct adjective. I'm getting an error on

System.out.println(sortedArray[index]);

and can't seem to figure out why. Any and all help is much appreciated.

Upvotes: 1

Views: 40

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You're assuming your input will be in ALL CAPS, but it isn't, so when you reach the 'b' in "Abe", you run into trouble. 'b' - 'A' is in effect 98 - 65 (33), as (int)'b' is 98 and (int)'A' is 65. 33 is out of range for the 0..25 (inclusive) array.

Make the character upper case before doing the subtraction. It's probably a good idea as well to check your input, e.g., don't assume the user isn't going to type something like '$' (which would give you the index -29). :-)

Upvotes: 2

Related Questions