java中的正则表达式模式/数组问题
我正在为下个月即将到来的考试而学习,并研究一些基本问题。这是一个程序,需要输入几个句子并重新打印包含特定字符串的任何句子,在本例中为“模式”
我的尝试如下所示,它已编译,但我在尝试运行它时收到以下错误:
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]);
}
}
}
}
# 1 楼答案
试试这个。它起作用了
小贴士: 确保使用nextLine(),以便输入内容能够阅读完整的句子。我将while循环切换为for循环中的if语句。那里不需要两个环路。我还把你的第一个for循环压缩成一行。如果只需要一秒钟,则无需创建字符串变量。只需完全跳过这一步,直奔主题!祝你好运,希望这有帮助
下面是一个反映您的程序,但现在可以运行了
下面是我如何编写这个程序的。包括澄清意见
# 2 楼答案
数组中有多少项?最后一个索引是什么?循环使用的最后一个索引是什么?你的循环总共访问多少个句子
# 3 楼答案
试一试
你会没事的:)
# 4 楼答案
<=
必须是<
,因为从0开始,有10个项目,所以i
必须从0到9# 5 楼答案
问题出在代码的第
:18
行,它是for (int i = 0; i <= sentences.length; i++)
,应该是for (int i = 0; i < sentences.length; i++)
当您在代码中的下一个
for
循环中使用<
而不是<=