好吧。我有一個try-catch塊,沒有問題,但是當我導入文本文件的第一行時,它說String index超出範圍:33。字符串索引超出範圍,來自文件的字符串輸入
該行是「牙醫拉出我的牙齒」 我正在做的是使用for循環來評估一行中的每個字符,直到我們到達所述行的末尾。如果該字符是元音,則增加元音整數。否則,如果它是一個空格,那麼我將空格改爲波浪號(〜)。我想知道的是爲什麼它說我的字符串超出範圍,我將如何將文本行中的空格從文件更改爲代字號。我可以自己把它輸出到不同的文件(這是我必須做的)。我只是爲什麼說它超出範圍而感到困惑。下面我粘貼了我的整個程序。
該程序的目標是評估一個文本文件,逐字符,並計數元音的數量。此外,我必須更改任何空格以便翻轉,然後重新輸出到不同的文本文件。
的代碼如下:
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileWriter;
public class Vowels {
public static void main(String[] args) {
Scanner inFile;
File dentist = new File("poetry.txt");
int vowels = 0;
try {
for (int i = 0; i >= 0; i++) {
inFile = new Scanner(new File("poetry.txt"));
String str1 = inFile.nextLine();
for (int a = 0; a >= 0; a++) {
String start;
start = str1.substring(a, a + 1);
if (start.equalsIgnoreCase("a") == true)
vowels++;
else if (start.equalsIgnoreCase("e") == true)
vowels++;
else if (start.equalsIgnoreCase("i") == true)
vowels++;
else if (start.equalsIgnoreCase("o") == true)
vowels++;
else if (start.equalsIgnoreCase("u") == true)
vowels++;
else if (start.equalsIgnoreCase(" "))
start = " ";
}
}
} catch (IOException i) {
System.out.println("Error");
}
}
}
你有調試過這個問題嗎? –
您正在for循環內打開文件...我不認爲這是個好主意。 – SuperPrograman
作爲提示,您可能需要考慮您正在使用什麼條件來結束for循環。 – SimonC