[英]I can't find the reason for “java.lang.StringIndexOutOfBoundsException” error
My code takes the first and last words of a user input and turns them into uppercase. 我的代码将用户输入的首尾两个单词转换为大写。 However, when the user enters "" or "java"(word without spaces) an error pops up.
但是,当用户输入“”或“ java”(不带空格的单词)时,会弹出错误。 I could not find the reason for the error.
我找不到错误的原因。
Scanner input = new Scanner(System.in);
String s = input.nextLine();
String first = "";
String last = "";
String end = s;
int count = 0;
for (int i = 0;i<s.length()-1;i++) {
if (s.charAt(i) == ' ') {
count++;
}
if (count == 0) {
end = s.toUpperCase();
}
else if (count > 0)
first = s.substring(0,s.indexOf(' '));
last = s.substring(s.lastIndexOf(' ')+1);
end = (first.toUpperCase() + " " + s.substring(first.length()+1,s.indexOf(last)) + " " +last.toUpperCase());
}
System.out.println(count);
String first = s.substring(0,s.indexOf(' '));
String last = s.substring(s.lastIndexOf(' ')+1);
Your code here is causing the problem. 您的代码在这里导致了问题。 If a space is not present in your
String
then indexOf(' ')
will return -1. 如果您的
String
没有空格,则indexOf(' ')
将返回-1。 You obviously can't substring between 0 and -1. 您显然不能在0到-1之间进行子字符串化。 You need to check if
' '
is present in the String
before you substring it. 您需要先检查
String
是否包含' '
,然后再对其进行子字符串化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.