简体   繁体   中英

Why am I getting this StringIndexOutOfBoundsException on executing code?

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

This is code for the following question:

Write a program to accept a sentence and print only the first letter of each word of the sentence in capital letters separated by a full stop. Example:

INPUT SENTENCE : "This is a Cat"
OUTPUT : TIAC

But when I execute the code I get

StringIndexOutOfBoundsException: String index out of range: 0

How do I fix this?

There are several issues :

    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
    }

Simply split your input with space .

See below code snippet

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

Please understand errors in your code as @Eran pointed then see how the above code works. That's how you need to learn :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM