royladd
royladd

Reputation: 13

Java int array and char array implementation: why does this work?

I am working on the Kattis problem "abc" in a programming seminar class. The question asks you to input three ints between 0 and 100, and have them match the pattern of another group of three char inputs with the case: A < B < C. Here 'A' will be int with least value, 'B' will be second greatest value, etc. I determined my logic but was unsure how to match values to char. Then a fellow student gave me help with the last line but I didn't get a chance to ask about how it worked. Code I have is as follows:

public class ABC {
    public static void main(String[] args) {
        var scanner = new Scanner(System.in);
        int[] num = new int[3];
        for (int i=0; i<num.length; i++) {
            num[i] = scanner.nextInt();
        }
        Arrays.sort(num);
        char[] chArr = scanner.next().toCharArray();
        for (int i=0; i<chArr.length; i++) {
            System.out.println(num[chArr[i] - 'A']); //How does num[chArr[i] - 'A'] work?            
        }
    }
}

Input:

1 2 3

C A B

Output:

3 1 2

So, my question is: How does the expression in the println at the end work? I'm a noob to posting on SO, so any suggestions would be gratefully accepted.

Upvotes: 1

Views: 109

Answers (2)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

A char in C is literally just an 8-bit integer. It tends to be used to represent ASCII characters, but in code it's an integer. Or in other words, char and uint8 are essentially the same type (in fact, one is an alias for the other in most implementations).

This relationship persists, in some form, into Java. A char is fundamentally an integer that presents itself as a character. Thus, you can do integer arithmetic with characters.

To examine num[chArr[i] - 'A']:

  1. chArr[i] retrieves the character at index i of chArr, an array of chars. Say this is 'C'.
  2. Note that the ASCII value of 'C' is 67.
  3. Note that the ASCII value of 'A' is 65.
  4. 67 - 65 = 2. So, 'C' is the 3rd letter of the alphabet, meaning it corresponds to index 2 of num.
  5. Retrieve the value at index 2 of num, and print it.

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

It's quite easy to understand:

Example :

char a = 'a';
char b = 'b';

// zero = 0 a this point
int zero = a - 'a';

// one = 1; and so on 
int one = b - 'b';  

Now in your case:

// is equivalent to whatever you enter and the difference of 'A'.
num[chArr[i] - 'A'] 

But if you enter something whose difference with A is more than the size of nums you are going to get an Array out bounds exception.

Upvotes: 0

Related Questions