我已经做了一段时间了,但正如标题所说,我正在尝试创建一个方法,将每个字母与后面的字母进行比较,看看单词是否在上升。然后,该方法应该返回一个布尔值。但是,当它在我的代码中实现时,它将失败,因为:
java.lang.StringIndexOutOfBoundsException:超出范围的字符串索引:1 在java.lang.String.charAt(未知来源)
还有其他多行错误代码。这是我的源代码:
public static boolean ascending(String word){
int i = 0;
boolean ascend;
do {
if (word.charAt(i) <= word.charAt(i+1))
ascend = false;
else
ascend = true;
} while (i <= word.length());
i = 0;
return (ascend);
}我看不出我哪里出了问题?
发布于 2013-10-23 19:54:53
条件应该是
i < word.length()-1末端的i = 0;应该和i++一样在循环的旁边,否则它将是无限循环。
另外,你实际上把反向检查。一旦修复了ArrayIndexOutOfBoundsException,您将返回升序字符串的false,否则返回true
public static boolean ascending(String word){
if(word == null || word.length <2) return false;
int i = 0;
boolean ascend = false;
while(i < word.length()-1){
if (word.charAt(i) <= word.charAt(i+1))
ascend = true;
else{
ascend = false;
break;
}
i++;
}
return (ascend);
}发布于 2013-10-23 19:56:45
我不使用do,因为有机会在一个空字符串上运行它,导致它崩溃。相反,我将在开始测试时使用一个常规的while (i < word.length()-1)。您永远不希望测试过字符串的末尾。您总是希望查看字符串长度为n的字符串长度是否为charAt(n-1) < charAt(n)。而且,我没有看到一个增量器来增加I..循环的值,它永远不会继续到下一个字母,并且将永远运行。
public static boolean ascending(String word){
int i = 0;
boolean ascend;
while (i < word.length()-1)
{
if (word.charAt(i) <= word.charAt(i+1))
ascend = false;
else
ascend = true;
i++;
}
i = 0;
return (ascend);
}发布于 2013-10-23 19:58:28
在伪码中:
https://stackoverflow.com/questions/19550984
复制相似问题