在Java中,当将类型转换后的数字用作数组索引时出现错误。

huangapple go评论96阅读模式
英文:

Getting error while taking typecasted number as index in array In Java

问题

这段代码的问题在于数组索引超出范围,导致 java.lang.ArrayIndexOutOfBoundsException 异常。错误发生在以下行:

int cn =(int)str.charAt(0);
System.out.println(table[cn]);

原因是 table 数组的长度是10,索引的范围应该在0到9之间,但你尝试使用 cn 作为索引,它的值是输入字符串 str 的第一个字符的ASCII码值。在输入为 "12" 时,ASCII码值为 49,超出了 table 数组的有效索引范围。

要修复这个错误,你需要将输入字符映射到正确的数组索引,可以使用以下方法:

int cn = Integer.parseInt(str); // 将输入字符串转换为整数
if (cn >= 0 && cn < table.length) {
    System.out.println(table[cn]);
} else {
    System.out.println("Invalid input");
}

这将把输入字符串转换为整数,并检查它是否在有效的索引范围内。如果不在范围内,会输出 "Invalid input"。

英文:
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
		String table[] = { &quot; &quot;, &quot;.+@$&quot;, &quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;, &quot;jkl&quot; , &quot;mno&quot;, &quot;pqrs&quot; , &quot;tuv&quot;, &quot;wxyz&quot; };
		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?

答案1

得分: 2

.charAt() 方法返回一个字符,当你将其解析为 int 时,它将给出该字符的 ASCII 值。

例如,如果你输入 12str.charAt(0) 将返回 &#39;1&#39;,将此字符转换为 int 将给出 49(字符 1 的 ASCII 值),而索引号 49 超出了 table 数组的界限。

解决方法:

你可以通过将 str.charAt(0) 的返回值作为参数传递给 String.valueOf(),将 .charAt() 方法返回的字符转换为 String,然后通过将 String.valueOf() 的返回值作为参数传递给 Integer.parseInt() 将该 String 解析为 int 类型。

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)));   // &lt;-----
    
    System.out.println(table[cn]);
}

你还可以使用 + 运算符将 str.charAt(0) 与一个空的 String 连接,然后将生成的 String 传递给 Integer.parseInt()

int cn = Integer.parseInt("" + str.charAt(0));
英文:

.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 &#39;1&#39; 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[] = { &quot; &quot;, &quot;.+@$&quot;, &quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;, &quot;jkl&quot; , &quot;mno&quot;, &quot;pqrs&quot; , &quot;tuv&quot;, &quot;wxyz&quot; };
    String str = sc.nextLine();
    
    int cn = Integer.parseInt(String.valueOf(str.charAt(0)));   // &lt;-----
    
    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(&quot;&quot; + str.charAt(0));

答案2

得分: 2

如Yousaf所提到的,你正在将字符强制转换为整数,因此你得到的是字符的ASCII值而不是数字。要使它工作,请更新你的代码中的这行:

int cn =(int)str.charAt(0);

改为:

int cn = Integer.parseInt(String.valueOf(str.charAt(0)));
英文:

As Yousaf mentioned you are typecasting character to int , hence you are getting the ascii value of the character and not the number . To make it work please update the this line of your code

int cn =(int)str.charAt(0);

to

int cn = Integer.parseInt(String.valueOf(str.charAt(0)));

答案3

得分: 1

我建议您使用以下代码:

int cn = Integer.parseInt(sc.nextLine().charAt(0));
英文:

I recommend you use this:

int cn = Integer.parseInt(sc.nextLine().charAt(0));

instead.

huangapple
  • 本文由 发表于 2020年7月22日 19:34:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63033250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定