[英]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 输出:TIAC
But when I execute the code I get 但是当我执行代码时,我得到了
StringIndexOutOfBoundsException: String index out of range: 0 StringIndexOutOfBoundsException:字符串索引超出范围: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. 请理解@Eran指出的代码中的错误,然后查看上面的代码如何工作。 That's how you need to learn :) 那就是你需要学习的方式:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.