[英]String index out of bounds? (Java, substring loop)
我正在为COSC课程制作的该程序编译不正确,但我不断收到错误消息:
线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:2
在VowelCount.main(VowelCount.java:13)在java.lang.String.substring(String.java:1765)
这是我的代码:
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input, letter;
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter a string: ");
input = scan.nextLine();
while (count <= input.length() ) {
letter = input.substring(count, (count + 1));
if (letter == "a") {
a++; }
if (letter == "e") {
e++; }
if (letter == "i") {
i++; }
if (letter == "o") {
o++; }
if (letter == "u") {
u++; }
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
据我所知,这应该起作用,但是为什么不起作用呢? 任何帮助都会很棒。 谢谢!
您可能需要删除行中的=
while (count <= input.length() ) {
并使其
while (count < input.length() ) {
因为它导致子字符串读取超出字符串长度。
==================但我会添加一些额外的建议,即使它并不需要:
不要使用==比较字符串,请使用
letter.equals("a")
代替。 甚至更好,请尝试使用
char c = input.charAt(count);
获取当前字符,然后像这样进行比较:
c == 'a'
删除等号应该可以解决该问题。
while (count < input.length()) {
并且由于要获得单个字符,因此应执行以下操作:
substr(count,1)
因为第二个参数实际上是长度,而不是索引。
我认为您的循环条件应为count < input.length
。 现在,最后一次迭代以count == length
运行,因此substring
调用在字符串中的最后一个字符之后被赋予起始索引,这是非法的。 在编写此类循环时,这类边界错误非常常见,因此,当遇到此类错误时,最好对循环条件进行两次和三次检查。
另外,将字符串与==
运算符进行比较通常不会做您想要的事情。 比较两个变量是否引用相同的对象。 相反,您要测试string1.equals(string2)
,它比较两个字符串的内容。
在所有人(尤其是文森特)的帮助下进行了修复。 谢谢! 运行出色。
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input;
char letter;
Scanner scan = new Scanner (System.in);
System.out.print ("Please enter a string: ");
input = scan.nextLine();
while (count < input.length() ) {
letter = input.charAt (count);
if (letter == 'a')
a++;
if (letter == 'e')
e++;
if (letter == 'i')
i++;
if (letter == 'o')
o++;
if (letter == 'u')
u++;
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
循环前,请尝试以下
if(input.length()>0){
//you code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.