为什么我在执行代码时得到这个字符串索引出界异常


import java.io.* ;
class Specimen
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please input the sentence :");
        String s= String.valueOf(bf.readLine());
        System.out.println(s);
        int index ;
        String modif="",part ;
        int c =0 ;
        char ch ;
        String part2;
        while(s.length()>0)
        {
            index = s.indexOf(' ');
            part = s.substring(c,index);
            part = part.trim();
            ch  = part.charAt(0);
            String s1 = String.valueOf(ch);
            modif = modif+ s1.toUpperCase()+".";
            c = index ;
        }
        System.out.println(modif);
    }
}

这是以下问题的代码:

编写一个程序来接受一个句子,并仅以大写字母打印句子中每个单词的第一个字母,并用句号分隔。 例:

输入句子:"这是一只猫">
输出 : T.I.A.C.

但是当我执行代码时,我得到

字符串索引

越界异常:字符串索引超出范围:0

我该如何解决这个问题?

有几个问题:

    while(s.length()>0) // this is an infinite loop, since s never changes
    {
        index = s.indexOf(' '); // this will always return the index of the first empty 
                                // space or -1 if there are no spaces at all
                                // use index = s.indexOf(' ',c);
        part = s.substring(c,index); // will fail if index is -1
        part = part.trim();
        ch  = part.charAt(0); // will throw an exception if part is an empty String
        String s1 = String.valueOf(ch);
        modif = modif+ s1.toUpperCase()+".";
        c = index ; // this should be c = index + 1
    }

只需用空格拆分您的输入即可。

请参阅下面的代码片段

public static void main(String[] args) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Please input the sentence :");
    String s = String.valueOf(bf.readLine());
    System.out.println(s);
    String output = "";
    String[] words = s.split(" ");
    for (String word : words) {
        if (word != null && !word.trim().isEmpty()) {
            output = output + word.charAt(0) + ".";
        }
    }
    System.out.println(output.toUpperCase());
}

请理解代码中的错误,@Eran指出,然后查看上面的代码是如何工作的。这就是你需要学习:)的方式

最新更新