kina
kina

Reputation: 45

How to use charAt to find the location of a char in a string

So I didn't want to use the ascii table to do this. I want to make the user input an alphanumeric(eg A3) and then take the alphabet(A) and find it in the string ABC so itll give me a number between 1-9 instead of having the ascii values. This will make it easier for me to put in a 2d array later.

However when I use System.out.println(abc.charAt(row)); itll say its out of bound bexception because its using the ascii value. How can I make it so that it doesn't

        public static void main(String[]args){
        Scanner k = new Scanner(System.in);
        String abc = "ABCDEFGHIJ";
        String ab = "abcdefghij";
        abc.equals(ab);
        System.out.println("Please enter the attack location:");

            while (!k.hasNext("[A-J a-j]+[0-9]")) {
                System.out.println("Wrong");
                k.next();
            }

            String location = k.next();
            char row = location.charAt(0);
            int num = (int) location.charAt(1);
            System.out.println(abc.charAt(row));
}
}

Upvotes: 0

Views: 501

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Remember, the ascii character for A starts at 65, so if the user enters A3, then you're actually using abc.charAt(65), which obviously is not what you want.

Instead, you need to find the index of the character in the array...

int index = abc.indexOf(row);

Have a look at String#indexOf for more details

You may also want to use Character.toUpperCase to convert the char the user entered to uppercase, which will make it easier to search your String

ps- Also something like row - 65 (or row - 'A' if that's to hard to remember) would give you the same result ;)

Upvotes: 2

Related Questions