【发布时间】:2014-09-22 17:26:12
【问题描述】:
我正在阅读关于字符串的 K&B。对于一些额外的知识,我正在阅读 Oracle 的教程。我正在从 Oracle 复制源代码。
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an
// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}
String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
//Testing getChars method //1
palindrome.getChars(0, len, tempCharArray, 1);
String tempString = new String(tempCharArray);
System.out.println(tempString);
}
}
我在源代码中添加了第 1 点。我正在理解 getChars 方法。当我运行它时,这个程序给了我 ArrayIndexOutOfBoundsException。这是我在字符串文档中读到的内容。
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
抛出:IndexOutOfBoundsException - 如果以下任何一项为真: srcBegin 是负数。 srcBegin 大于 srcEnd srcEnd 是 大于这个字符串的长度 dstBegin 是负数 dstBegin+(srcEnd-srcBegin) 大于 dst.length
destBegin 是什么?什么偏移量,文档正在谈论。 1 是目标数组中的有效偏移量。请帮我解决这个困惑。
谢谢。
【问题讨论】:
-
您可以在问题中添加源字符串和目标字符串吗?这可能有助于我们澄清为什么它会越界。
-
不确定是什么问题... 1 是一个有效的偏移量
-
@JasonD 源字符串包含在程序中。
-
错过了,它在回文中:)