Brad
Brad

Reputation: 202

Processing parallel arrays

For my Java assignment, I have to compare values and/or indexes in several different arrays. The assignment calls for prompting the user to enter five letters (upper or lowercase), and to store those in an array “lettersArray”. I also have two other arrays; a char array called “asciiArray” with all the upper and lowercase characters (so 52 indexes) and an int array called “decimalArray” that contains the corresponding decimal values of the english characters (also with 52 indexes).

I’m then supposed to pass those to a second method. This second method needs to determine the decimal values of the letters that the user has entered. This is where I’m getting confused. I’ve pseudocoded this a hundred times today and just can’t see where I’m going wrong. I need to compare every value in lettersArray to all the values in asciiArray to find the match, then get the value from the corresponding index of decimalArray. When I print the decimalArray to check the values, they’re all over the place.

For example, when I input the characters a, s, d, f, and g, I get 91, 109, 94, 96, and 97. These values seem totally random to me and I haven’t been able to figure out where my program is screwing up. I’ll buy you all the beers if you can help at all!

public class AverageLetter {
public static void main(String [] args) {
    Scanner read = new Scanner(System.in);
    char letterArray[] = new char[5];
    System.out.println("Enter 5 English letters (a-z or A-Z): ");

    for(int i = 0; i < 5; i++) {
        System.out.print("Letter " + (i+1) + ": ");
        letterArray[i] = read.next().charAt(0);
    }

    String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    char[] asciiArray = characters.toCharArray();
    int[] decimalArray = new int[52];

    for (int i=0; i<decimalArray.length; i++ ) {
        decimalArray[i] = 65+i;
    }

    getAverage(letterArray, asciiArray, decimalArray);
}

public static void getAverage(char[] letter, char[] ascii, int[] decimal) {
    for(int i = 0; i < letter.length; i++) {
        for(int j = 0; j < ascii.length; j++) {
            if(letter[i] == ascii[j]) {
                     System.out.print(decimal[j] + " ");
            }
        }
    }
}

Upvotes: 0

Views: 542

Answers (1)

Byron Lo
Byron Lo

Reputation: 464

Take a look at ASCII values 91 through 96. These symbols were not taken into account in your 'characters' array.

    "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz"

This is what you want.

I'm not sure why you are using separate arrays, one for characters between A-z and one for their integer values.

You can easily cast the user's character inputs into an 'int'.

    int val = (int) letters[i];

No need to do separate lookups. (you should also make sure that the character's from your user's input are letter as well).

Upvotes: 3

Related Questions