[英]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.