這個節目,我正在做一個COSC當然不是編譯吧,我不斷收到錯誤:螺紋字符串索引超出範圍? (Java中,子環)
異常「主要」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:2
在java.lang.String.substring(String.java:1765) 在VowelCount.main(VowelCount.java:13)
這裏是我的代碼:
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.");
}
}
要我的知識邊緣這應該工作,但爲什麼不呢?任何幫助都會很棒。謝謝!
好吧,它編譯!但仍然沒有輸出正確的金額。測試字符串「aeiou」結果爲0,0,0,0,0 .. – Brad 2009-10-15 01:39:21
更改爲'substr(count,1)' – mauris 2009-10-15 01:42:03
不要使用==來比較字符串,如其他答案 – 2009-10-15 01:42:59