![](/img/trans.png)
[英]Why am I getting StringIndexOutOfBoundsException in this code?
[英]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);
}
}
这是以下问题的代码:
编写一个程序以接受一个句子,并仅将句子中每个单词的第一个字母打印为大写字母,并用句号分隔。 例:
输入句:“这是猫”
输出:TIAC
但是当我执行代码时,我得到了
StringIndexOutOfBoundsException:字符串索引超出范围: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指出的代码中的错误,然后查看上面的代码如何工作。 那就是你需要学习的方式:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.