可以,然后呢。我有一个try-catch块,没有问题,但是问题是,当我导入文本文件的第一行时,它说String索引超出范围: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(int i = 0; i>=0; i++){
inFile = new Scanner(new File("poetry.txt"));
String str1 = inFile.nextLine();



那将循环几乎2 ^ 32/2-1次。
每次都会创建一个新的Scanner对象。
您每次都在第一次阅读。

for(int a = 0; a >= 0; a++) {
    String start;
    start = str1.substring(a, a + 1);
}

这将再次循环2 ^ 32/2-1次。

由于str1不如变量“ a”大,因此崩溃。您需要使此循环为

for(int a = 0; a < (str1.length() - 1); a++) {
    String start = str1.substring(a, a + 1);
}



这应该可以解决您的问题。

关于java - 字符串索引超出范围,从文件输入字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19762141/

10-10 12:56
查看更多