gpt4 book ai didi

java - 为什么我在执行代码时会收到此 StringIndexOutOfBoundsException?

转载 作者:行者123 更新时间:2023-12-01 22:00:27 25 4
gpt4 key购买 nike

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

这是以下问题的代码:

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 : T.I.A.C.

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

StringIndexOutOfBoundsException: String index out of range: 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
}

关于java - 为什么我在执行代码时会收到此 StringIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com