I am working on the game where the columns of the board are represented by the characters but i would like to assign them an index. I have decided to use the switch statement in that case, however it does produce the wrong result. With the current code I attach, it gives me 14 as an index, however since the string is 7h, and it takes h as a char, it should give an index of 7. What Could be an issue? Thanks in advance!
public class Check < public int columnToInt(char c) < int index=0; switch(c) < case 'a': index=0; case 'b': index=1; case 'c': index=2; case 'd': index=3; case 'e': index=4; case 'f': index=5; case 'g': index=6; case 'h': index=7; case 'i': index=8; case 'j': index=9; case 'k': index=10; case 'l': index=11; case 'm': index=12; case 'n': index=13; case 'o': index=14; >return index; > public static void main(String[] args) < String myStr = "7h"; char c =myStr.charAt(1); System.out.println("the char at position 1 is "+c); Check check = new Check(); int result = check.columnToInt(c); System.out.println(result); >>
asked Jan 7, 2022 at 17:53
11 3 3 bronze badges
you forgot to use break in each case
Commented Jan 7, 2022 at 17:56
Do not use switch statements, do what @ScottHunter sent you. Also your code is wrong because you don't use breaks after each case.
Commented Jan 7, 2022 at 17:57@ScottHunter the OP is not converting a char into its ASCII value. The OP is looking kind of simulating locating the given char in a char[] .
Commented Jan 7, 2022 at 18:02I have a better solution, but the question is closed. So, here is my recommendation to you. Create a list of characters like this as a global field of the Check class: private List