Reputation: 3
I was reading about matrx in java and I found this method in my course page :
public int getSeatStatus(int row, char ch) { // Returns the status of the seat (row, ch)
return seats[row][(ch - ’A’)].getStatus();
}
I do not understand how the method works .. as you can see that ch is not an index so why do they use it as an index ?
Can we rewrite this code in another simple way ? for example I tried to rewrite it like this :
public int getSeatStatus(int row, char ch){
int col = 0;
if (ch == 'A') {
col=0;
} else if (ch == 'B') {
col=1;
}
return s[row][col].getStatus();
}
Am I doing right ? Thanks
Upvotes: 0
Views: 353
Reputation: 726
In Java, char
is a numeric type. When you do char - ’A’
, you operate with unicode code point. In case of 'A' - 'A'
, result is 0, when 'B' - 'A'
result is 1, etc. It gives array indexes.
Upvotes: 1
Reputation: 8239
According to the ASCII standard the letter A
has an integer value of 65
and Z
of 90
.
So, if you subtract A
from the value of the given parameter, you get a value:
('B' - 'A') = (66 - 65) = 1
('F' - 'A') = (70 - 65) = 5
If you wanted to rewrite the rule for the whole alphabet, you would have to write 26 cases of recurring code.
Upvotes: 1
Reputation: 1275
You can convert a Character into an Integer. So you can also use it as an index.
For example the output for System.out.println(0 + 'A')
is 65.
Upvotes: 1
Reputation: 537
I wouldn't do it like that... If you have two 'ch' objects it's managable with if statements, but what if you have a 100? It would mean a unmaintable amount of if statements.
If you cast char 'A' to an int, the value is 65. By doing
ch - 'A'
you get 65 - 65 corresponding with index 0.
If you cast char 'B' to an int, the value is 66. By doing ch - 'A'
you get 66 - 65 corresponding with 1.
Your first example is in fact a better way to do this, and will work, even if the seats are "numbered" A till Z.
Upvotes: 2