Java 当char没有值时,如何避免StringIndexOutOfBoundsException?
对不起,如果标题没有意义,但我不知道如何用词 问题是: 我正在做一个选择题问答游戏,从用户那里得到a、b、c或d。如果他们按照要求去做,这是没有问题的,但是如果他们不键入任何内容,只按enter键,我会得到一个StringIndexOutOfBoundsException。我理解为什么会发生这种情况,但我对Java是新手,想不出一种方法来修复它 到目前为止,我所拥有的:Java 当char没有值时,如何避免StringIndexOutOfBoundsException?,java,null,char,Java,Null,Char,对不起,如果标题没有意义,但我不知道如何用词 问题是: 我正在做一个选择题问答游戏,从用户那里得到a、b、c或d。如果他们按照要求去做,这是没有问题的,但是如果他们不键入任何内容,只按enter键,我会得到一个StringIndexOutOfBoundsException。我理解为什么会发生这种情况,但我对Java是新手,想不出一种方法来修复它 到目前为止,我所拥有的: System.out.println("Enter the Answer."); response = in
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");
}
当然,如果用户不键入任何内容,程序将永远无法通过第二行代码,因为不能接受空字符串的charAt(0)值。我要寻找的是一种可以检查响应是否为空的东西,如果是,请返回并再次向用户提问
提前感谢您的回答。简单:
- 最初以字符串形式获取输入,并将其放入临时字符串变量中
- 然后检查字符串的长度李>
- 然后,如果>0,则提取第一个字符并使用它
StringIndexOutOfBoundsException
)或中断此语句
response = input.nextLine().charAt(0);
作为
异常处理:
try{
response = input.nextLine().charAt(0);
}catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
您可以使用do-while循环。替换
response = input.nextLine().charAt(0);
与
字符串行;
做{
line=input.nextLine();
}while(line.length()<1);
响应=行字符(0);
当用户输入一个空行时,这将继续调用
input.nextLine()
,但一旦用户输入一个非空行,它将继续并将response
设置为该非空行的第一个字符。如果要重新提示用户输入答案,则可以将提示添加到循环内部。如果您想检查用户是否输入了字母a–d,您还可以将该逻辑添加到循环条件中。此外@hovercraftfullofels(完全有效)回答,我想指出,您可以“捕获”这些异常。例如:
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.如果在执行
try
-块时遇到StringIndexOutOfBoundsException
,将执行catch
-块中的代码。您可以阅读有关捕获和处理异常的更多信息。StringIndexOutofBoundException在以下情况下也会发生
temp=“和”
字符串arr[]={“android”、“jellybean”、“kitkat”、“ax”}
对于(int index=0;index
如果(temp.length()我假设
input
类型为java.util.Scanner
。如果是这种情况,那么它将实际返回一个空字符串,而不是null
。是的,它将是空字符串。这就是为什么input.nextLine().charAt(0);
将生成一个StringIndexOutOBoundsExceptionCaninput.nextLine()
是否为null
?@A.R.S.:在长度检查之前放置null检查已成为我的习惯。已删除。
String line;
do {
line = input.nextLine();
} while (line.length() < 1);
response = line.charAt(0);
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
}