chasing鱼 2023-06-05 18:43 采纳率: 47.1%
浏览 38
已结题

java.lang.StringIndexOutOfBoundsException: String index out of range: 0

img

一个循环结构,第一次循环时,调用这个方法能正常运行。第二次循环调用这个方法就出错了,我测试之后,发现readKeyBoard()方法里的while循环里的语句在第二次就没运行,字符串的长度就直接是0了,控制台输入直接没运行,该怎么改呢?

public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);
            c = str.charAt(0);
            if (c != '1' && c != '2' && 
                c != '3' && c != '4' && c != '5') {
                System.out.print("选择错误,请重新输入:");
            } else break;
        }
        return c;
    }


 private static String readKeyBoard(int limit, boolean blankReturn) {
        String line = "";

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.length() == 0) {
                if (blankReturn) return line;
                else continue;
            }

            if (line.length() < 1 || line.length() > limit) {
                System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
                continue;
            }
            break;
        }

        return line;
    }


  • 写回答

2条回答 默认 最新

  • Soulic 2023-06-05 19:12
    关注

    在c = str.charAt(0)之前判断下str的长度,长度小于1时continue。代码没有错,看下你是怎么输入的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月14日
  • 已采纳回答 6月6日
  • 创建了问题 6月5日