为什么我在执行代码时遇到这个StringIndexOutOfBoundsException?

时间:2015-11-09 08:39:24

标签: java exception

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);
    }
}

这是以下问题的代码:

  

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

     
    

INPUT SENTENCE:"这是Cat"
    输出:T.I.A.C。

  

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

  

StringIndexOutOfBoundsException:字符串索引超出范围:0

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

有几个问题:

    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
    }

答案 1 :(得分: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指出,然后查看上述代码的工作原理。这就是你需要学习的方法:)

相关问题