我正在为下个月即将到来的考试而学习,并研究一些基本问题。这是一个程序,需要输入几个句子并重新打印包含特定字符串的任何句子,在这种情况下为“模式”。
我的尝试如下,它编译但是我在尝试运行它时收到以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Grep.main(Grep.java:18)
import java.util.Scanner;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Grep {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[Pp]attern");
String sentences[] = new String[10];
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter some sentences: ");
for (int i = 0; i <= sentences.length; i++) {
String s = scanner.next();
sentences[i] = s;
}
for (int i = 0; i < sentences.length; i++) {
Matcher matcher = pattern.matcher(sentences[i]);
while (matcher.find()) {
System.out.println(sentences[i]);
}
}
}
}