简体   繁体   中英

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.

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, eg, don't assume the user isn't going to type something like '$' (which would give you the index -29 ). :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM