java 当 char 没有值时,如何避免 StringIndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13004631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I avoid StringIndexOutOfBoundsException when char has no value?
提问by hashtag name
Sorry if the title made no sense but I did not know how to word it.
对不起,如果标题没有意义,但我不知道如何措辞。
The problem:
问题:
I'm making a multiple choice quiz game that gets either a, b, c or d from the user. This is no problem if they do as they are told, however if they don't type anything and just hit enter I get a StringIndexOutOfBoundsException. I understand why this is happening, but I'm new to Java and can't think of a way to fix it.
我正在制作一个多项选择测验游戏,从用户那里获得 a、b、c 或 d。如果他们按照他们的指示去做,这没有问题,但是如果他们不输入任何内容而只是按回车键,我会得到一个 StringIndexOutOfBoundsException。我明白为什么会发生这种情况,但我是 Java 新手,想不出解决方法。
What I have so far:
到目前为止我所拥有的:
System.out.println("Enter the Answer.");
response = input.nextLine().charAt(0);
if(response == 'a')
{
System.out.println("Correct");
}
else if(response == 'b' || response == 'c' || response == 'd')
{
System.out.println("Wrong");
}
else
{
System.out.println("Invalid");
}
Of course the program will never make it past the second line of code if the user types nothing, because you can't take the charAt(0) value of an empty String. What I'm looking for is something that will check if the response is null, and if so ask go back and ask the question to the user again.
当然,如果用户没有键入任何内容,程序将永远不会超过第二行代码,因为您不能获取空字符串的 charAt(0) 值。我正在寻找的是可以检查响应是否为空的东西,如果是,请返回并再次向用户提出问题。
Thanks in advance for any answers.
提前感谢您的任何答案。
采纳答案by DaoWen
You can use a do-while loop. Just replace
您可以使用 do-while 循环。只需更换
response = input.nextLine().charAt(0);
with
和
String line;
do {
line = input.nextLine();
} while (line.length() < 1);
response = line.charAt(0);
This will continue to call input.nextLine()
as many times as the user enters a blank line, but as soon as they enter a non-blank line it will continue and set response
equal to the first character of that non-blank line. If you want to re-prompt the user for the answer, then you could add the prompt to the inside of the loop. If you want to check that the user entered a letter a–d you could also add that logic to the loop condition.
这将继续调用input.nextLine()
与用户输入空行一样多的次数,但是一旦他们输入非空行,它将继续并设置为response
等于该非空行的第一个字符。如果您想重新提示用户提供答案,则可以将提示添加到循环内部。如果您想检查用户是否输入了字母 a–d,您还可以将该逻辑添加到循环条件中。
回答by Yogendra Singh
Either handle the exception(StringIndexOutOfBoundsException
) or break this statement
处理异常( StringIndexOutOfBoundsException
) 或中断此语句
response = input.nextLine().charAt(0);
as
作为
String line = input.nextLine();
if(line.length()>0){
response = line.charAt(0);
}
Exception Handling:
异常处理:
try{
response = input.nextLine().charAt(0);
}catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
回答by arshajii
In addition @HovercraftFullOfEels' (perfectly valid) answer, I'd like to point out that you can "catch" these exceptions. For example:
另外@HovercraftFullOfEels'(完全有效)的答案,我想指出你可以“捕捉”这些异常。例如:
try {
response = input.nextLine().charAt(0);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("You didn't enter a valid input!");
// or do anything else to hander invalid input
}
i.e. if a StringIndexOutOfBoundsException
is encountered when executing the try
-block, the code in the catch
-block will be executed. You can read more about catching and handling exceptions here.
即如果StringIndexOutOfBoundsException
在执行try
-block时遇到a ,将执行-block 中的代码catch
。您可以在此处阅读有关捕获和处理异常的更多信息。
回答by Hovercraft Full Of Eels
Simple:
简单的:
- Get the input initially as a String, and put it into a temporary String variable.
- Then check the String's length.
- then if > 0 extract the first char and use it.
- 最初以字符串形式获取输入,并将其放入临时字符串变量中。
- 然后检查字符串的长度。
- 然后 if > 0 提取第一个字符并使用它。
回答by Nantha kumar
StringIndexOutofBoundException will occur in the following situation also.
StringIndexOutofBoundException 在以下情况下也会发生。
- Searching a string which is not available
Match with the string which is not available
for ex:
List ans=new ArrayList();
temp="and";
String arr[]={"android","jellybean","kitkat","ax"};
for(int index=0;index < arr.length;index++ )
if(temp.length()<=arr[index].length())
if(temp.equlsIgnoreCase((String)arr[``index].subSequence(0,temp.length())));
ans.add(arr[index]);
- 搜索不可用的字符串
匹配不可用的字符串
例如:
列表 ans=new ArrayList();
温度=“和”;
String arr[]={"android","jellybean","kitkat","ax"};
for(int index=0;index < arr.length;index++)
if(temp.length()<=arr[index].length())
if(temp.equlsIgnoreCase((String)arr[``index].subSequence) (0,temp.length())));
ans.add(arr[index]);
the following code is required to avoid indexoutofboundexception
需要以下代码来避免 indexoutofboundexception
if(temp.length()<=arr[index].length())
if(temp.length()<=arr[index].length())
because here we are cheking the length of src string is equal or greater than temp . if the src string length is less than it will through "arrayindexoutof boundexception"
因为在这里我们正在检查 src 字符串的长度是否等于或大于 temp 。如果 src 字符串长度小于它会通过“arrayindexoutof boundexception”