public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String table[] = { " ", ".+@$", "abc", "def", "ghi", "jkl" , "mno", "pqrs" , "tuv", "wxyz" };
String str = sc.nextLine();
int cn =(int)str.charAt(0);
System.out.println(table[cn]);
}
}
For input 12 this code is giving me Error as :- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 49 at Main.main(Main.java:8)
can someone explain me why is this error coming and how to remove this error?
.charAt()
method returns a character and when you parse it into int
, it will give you the ascii value of that character.
For example, if you enter 12
, str.charAt(0)
will return '1'
and converting this character into int
will give you 49 (ascii value for character 1) and index number 49 is out of bounds for the table
array.
Solution:
You could convert the character returned by .charAt()
method into String
by passing the return value of str.charAt(0)
as an argument to String.valueOf()
and then parse that String
into an int
type by passing the return value of String.valueOf()
as an argument to Integer.parseInt()
.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String table[] = { " ", ".+@$", "abc", "def", "ghi", "jkl" , "mno", "pqrs" , "tuv", "wxyz" };
String str = sc.nextLine();
int cn = Integer.parseInt(String.valueOf(str.charAt(0))); // <-----
System.out.println(table[cn]);
}
You could also use +
operator to concatenate str.charAt(0)
with an empty String
and then pass the resulting String
to Integer.parseInt()
.
int cn = Integer.parseInt("" + str.charAt(0));