这个问题在这里已经有了答案:
什么是indexoutofboundsexception?我该怎么修[重复](1个答案)
上个月关门了。
public class DuplicateLetters {
// CW2.2 Lab-Group-06 Question 5
// You are given two non-empty strings source and target, all lowercase letters, from a user.
// The user intends to type the string given in target.
// However, due to using an old keyboard,
// when the user was typing, a number characters may be duplicated, and typed one or more times.
// The source is what the user actually typed, which may or may not be the intended target.
// Return true if and only if it is possible that some characters of target have been duplicated in source,
// while the user intended to type the target string.
// You must use String methods in lecture notes.
// You must NOT use StringBuilder or Regular Expression methods.
public static boolean duplicateLetters(String source, String target) {
boolean test = false;
for(int i=0; i<source.length(); i++) {
for(int j=i; j<target.length(); j++) {
if(Character.toString(source.charAt(i)).equals(Character.toString(target.charAt(j)))) {
test = true;
}
else {
test = false;
j--;
}
i++;
}
}
return test;
}
public static void main(String[] args) {
System.out.println(duplicateLetters("andddrew", "andrew"));
// true, there are duplicated letters typed
System.out.println(duplicateLetters("lllejiiee", "leejie"));
// false, note the initial letter e
// there is only one initial e in the source, whereas there is a double initial ee in the target
System.out.println(duplicateLetters("cherry", "cherry"));
// true, no duplicated letters typed this time
}
这是我针对这个问题编写的代码,但它不断得到java.lang.stringindexoutofbounds错误。所以,我想知道我的代码有什么问题,以及如何改进。
2条答案
按热度按时间fdx2calv1#
这是一个正确的运行版本。注意,您还需要检查与目标的最后一个不匹配的新字符是否匹配。
duplicateLetters("axbc", "");
否则就会失败(这仍将发生在鲁胡尔(ruhul)已经提出的指数修正案中。优化:
在目标上循环,以便更容易地检查目标中的双字母(例如“letter”和“lettttter”)。
出现问题时立即退出循环。你不需要继续,因为结果在任何情况下都是真实的。
y1aodyip2#
当
i
超越了source.length
发生异常。要解决此问题,请在比较或中断循环之前添加检查。例如:
你的逻辑也太复杂和错误了。因为纠正这些错误超出了范围,所以你应该自己去发现(家庭作业):p。