indexOf() 在查找空格时返回 -1

indexOf() returning -1 when looking for spaces

我在尝试分隔字符串中的单词时使用 indexOf() 查找空格,但索引关闭一直返回 -1;这是我的代码:-

import java.util.Scanner;

class Main {
  public static void main(String[] args){
    Scanner y = new Scanner(System.in);
    System.out.println("Enter the String");
    String s = y.nextLine();
    int words = 1;
    for (int i = 0; i < s.length(); i++) {
     if(s.charAt(i)==' ') words++;
    }
    String[] a = new String[words];
    int l = s.length();
    for (int i = 0; i <= words; i++) {
      int r = s.indexOf(" ");
      a[i] = s.substring(0, r);
      s = s.substring((r + 1), l);
    }
    for(int i = 0; i <= words; i++) {
      System.out.println(a[i]);
    }
  }
}

您可以只使用 String.split,例如:

String s=y.nextLine();
for(String i : s.split(" ")) {
   System.out.println(i);
}

问题是您从 words 开始,并为找到的每个 space 增加它。因此,如果有一个 space,words 就是 2。然后您试图寻找那么多 space - 但只有 1,所以当它用完 spaces 找到,它 returns -1 并且你得到异常。