I am studying for an upcoming test next month and looking at some basic problems. This one is a program that requires entering a few sentences and reprinting any that contain a certain string, 'pattern' in this case.
My attempt is below and it compiles however I receive the following error when trying to run it:
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]);
}
}
}
}