7

对不起,如果标题没有意义,但我不知道如何措辞。

问题:

我正在制作一个从用户那里获得 a、b、c 或 d 的多项选择测验游戏。如果他们按照他们的指示去做,这没有问题,但是如果他们不输入任何内容而只是按 Enter 键,我会得到一个 StringIndexOutOfBoundsException。我理解为什么会发生这种情况,但我是 Java 新手,想不出办法来解决它。

到目前为止我所拥有的:

    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) 值。我正在寻找的东西会检查响应是否为空,如果是这样,请返回并再次向用户提问。

提前感谢您的任何答案。

4

5 回答 5

6

您可以使用 do-while 循环。只需更换

response = input.nextLine().charAt(0);

String line;

do {
  line = input.nextLine();
} while (line.length() < 1);

response = line.charAt(0);

当用户输入一个空行时,这将继续调用input.nextLine()多次,但是一旦他们输入一个非空行,它将继续并设置response为该非空行的第一个字符。如果您想重新提示用户回答,则可以将提示添加到循环内部。如果您想检查用户是否输入了字母 a-d,您还可以将该逻辑添加到循环条件中。

于 2012-10-22T03:31:31.173 回答
3

要么处理异常(StringIndexOutOfBoundsException)要么打破这个语句

    response = input.nextLine().charAt(0);

作为

    String line = input.nextLine();
    if(line.length()>0){
        response = line.charAt(0);
    }

异常处理:

    try{
        response = input.nextLine().charAt(0);
    }catch(StringIndexOutOfBoundsException siobe){
        System.out.println("invalid input");
    }
于 2012-10-22T03:30:15.463 回答
2

简单的:

  • 最初以字符串形式获取输入,并将其放入临时字符串变量中。
  • 然后检查字符串的长度。
  • 然后如果 > 0 提取第一个字符并使用它。
于 2012-10-22T03:29:24.387 回答
2

除了@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
}

即如果在执行-blockStringIndexOutOfBoundsException时遇到a,将执行try-block 中的代码catch您可以在此处阅读有关捕获和处理异常的更多信息。

于 2012-10-22T03:31:34.587 回答
0

StringIndexOutofBoundException 在以下情况下也会发生。

  1. 搜索不可用的字符串
  2. 匹配不可用的字符串

    例如:

    列表 ans=new ArrayList();
    临时=“和”;
    字符串 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]);

需要以下代码以避免 indexoutofboundexception

if(temp.length()<=arr[index].length())

因为这里我们正在检查 src 字符串的长度是否等于或大于 temp 。如果 src 字符串长度小于它将通过“arrayindexoutof boundexception”

于 2013-11-16T09:17:03.040 回答