java - 输入空字符串 Java 时出现 StringIndexOutofBoundsException 错误
问题描述
嗨,每当我尝试输入空字符串时,我都会收到此错误。到目前为止,其他一切都有效,如果我在 String 内放置一个空格,它就可以工作。我知道这真的很挑剔,但我很好奇在这种情况下我应该做什么来确保它只返回一个空字符串。
**> HW2.nthWord(2,"")
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at HW2.nthWord(HW2.java:124)**
我确实创建了一个特殊实例,用于输入此值但它仍然不起作用。
我需要做什么来纠正这个问题?
/*nthWord takes an int and a String as input and returns a String:
The input int represents a number n that is assumed to be positive, and the output string
contains every nth word of the input string, starting with the first word, separated by a single space.
For this method, a word is defined to be a sequence of non-space characters.
There should be no space at the end of the output string.
*/
public static String nthWord( int number, String input ){
StringBuilder create = new StringBuilder();
int totalspaces = 0; //This is to hold a count of the number of spaces in a String
if( number == 0){
return input;
}
if(input == ""){
return input;
}
else{
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
for( int i = 0; i < input.length() - 1 ; i = i + 1){
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
if(totalspaces % number == 0 && totalspaces != 0){
create.append(' ');
for(int j = i+1; input.charAt(j) != ' ' && j < input.length(); j = j+1){
create.append(input.charAt(j));
i = j;
}
}
}
}
return create.toString();
}
}
解决方案
我注意到一些事情
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
这个循环将继续添加“输入”字符,直到它到达一个空格''字符。如果输入没有空格字符,则此循环将超出输入长度并导致错误。你可能想要这样的东西:
for(int i = 0; i < input.length(); i = i + 1){
if(input.charAt(i) == ' ' ){
break;
} else {
create.append(input.charAt(i));
}
}
此外,当您到达线路时:
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
您已经知道 i < input.length() - 1 因为您处于 for 循环中。您可以将该行更改为:
if(input.charAt(i) == ' ' && input.charAt(i+1) != ' '){
出于同样的原因,您的下一部分:
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
可以改为
if( i != input.length()-1 ){
totalspaces = totalspaces + 1;
}
另外,我注意到您可能使问题变得比需要的更难。如果您在单个 for 循环中解决问题,问题会容易得多。
for(int i = 0; i < input.length(); i = i + 1){
if( x ) //x is some code that determines if you are part of the nth word
create.append(input.charAt(i));
}
推荐阅读
- opencv - 图像计数线
- javascript - 如何通过服务器端渲染和与 redux 存储的集成正确获取 react-instantsearch 的 resultsState
- java - 如何为 JTable 中的行创建翻转或悬停效果?
- c# - 实例化变量不包含任何值
- ios - 防止从相同类型的 ViewController (ARC) 创建多个实例
- python - ValueError:形状必须为 2 级,但对于“MatMul”(操作:“MatMul”)为 1 级,输入形状为:[2]、[2,3]
- node.js - bcrypt-nodejs 比较函数总是返回 false
- java - Jenkins-Maven 构建失败:找不到主类:jenkins.maven3.agent.Maven32Main。程序将会退出
- python - Django中不同模型的输出
- css - 覆盖按比例大小的背景图像