字符串索引超出范围

字符串索引超出范围

我一直坚持下去,找不到解决方案。获取线程“主”中的Exception错误java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:11。

谁能帮助解决这个问题?
我的代码:

public static void main(String[] args) {
    try {
        Scanner sc = new Scanner(new File("Testing.txt"));
        int i = 0;

        while(sc.hasNext()){
            String line = sc.nextLine();
            char needle = line.charAt(i);

            while(i < line.length()){
                if(Character.isUpperCase(needle)) {
                    while(needle != ' '){
                        System.out.print(needle);
                        i++;
                        needle = line.charAt(i);
                    }
                    System.out.println(needle);
                }
                else{
                    i++;
                    needle = line.charAt(i);
               }
            }
        }
    }
    catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}

最佳答案

根据我的上述评论,将很容易使用String split方法。当然,可以用文件中的文本替换input,并使用expectedResult并测试输出是否相等,这完全是可选的

  public static void main(String[] args)
  {

      String input = "Kenny and I are eating in the Restaurant Yummy";
      String expectedResult = "Kenny, I, Restaurant, Yummy";
      String arr [] = input.split (" ");

      StringBuilder out = new StringBuilder();
      for (int i = 0; i < arr.length; i++) {
          if (Character.isUpperCase(arr[i].charAt(0))) {
              out.append(arr[i]).append(", ");
          }
      }

      if (out.length() > 1) {
          out.setLength(out.length() -2);
      }

      System.out.println (out);
      assert (expectedResult.equals(out.toString()));

  }


输出


  
    肯尼,我,餐厅,美味

10-06 03:20